代码之家  ›  专栏  ›  技术社区  ›  Esther

将特定于函数的对象中的值提取到数据帧中

  •  1
  • Esther  · 技术社区  · 6 年前

    我正在尝试绘制函数多次运行的结果。函数返回具有不同长度列表的对象。

    library(ldbounds)
    reas1.lin = bounds(t = c(.5,.75,1),iuse = c(3,3),alpha = c(0.025,0.025))
    

    结果如下所示:

    $bounds.type
    [1] 2
    
    $spending.type
    [1] "Power Family: alpha * t^phi"
    
    $time
    [1] 0.50 0.75 1.00
    
    $time2
    [1] 0.50 0.75 1.00
    
    $alpha
    [1] 0.025 0.025
    
    $overall.alpha
    [1] 0.05
    
    $lower.bounds
    [1] -2.241403 -2.288491 -2.229551
    
    $upper.bounds
    [1] 2.241403 2.288491 2.229551
    
    $exit.pr
    [1] 0.0250 0.0375 0.0500
    
    $diff.pr
    [1] 0.0250 0.0125 0.0125
    
    attr(,"class")
    [1] "bounds"
    

    我想得到如下数据帧:

    time1 time2 lower.bound upper.bound exit.pr diffpr                        type 
    0.50  0.50   -2.241403    2.241403  0.0250 0.0250 Power Family: alpha * t^phi       
    0.75  0.75   -2.288491    2.288491  0.0375 0.0125 Power Family: alpha * t^phi       
    1.00  1.00   -2.229551    2.229551  0.0500 0.0125 Power Family: alpha * t^phi       
    

    这就是我如何将数据提取到上面的数据框中,但这取决于每个列表中的元素数量,必须有一个更优雅的解决方案。。。

    example1.lin <- data.frame(matrix(as.numeric(unlist(reas1.lin)[c(3:8,12:23)]), 
                        nrow=3,
                        byrow=F),type=reas1.lin$spending.type)
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Julius Vainora    6 年前

    有一种方法:

    nms <- c("time", "time2", "lower.bounds", "upper.bounds", "exit.pr", "diff.pr", "spending.type")
    as.data.frame(reas1.lin[nms])
    #   time time2 lower.bounds upper.bounds exit.pr diff.pr               spending.type
    # 1 0.50  0.50    -2.241403     2.241403  0.0250  0.0250 Power Family: alpha * t^phi
    # 2 0.75  0.75    -2.288491     2.288491  0.0375  0.0125 Power Family: alpha * t^phi
    # 3 1.00  1.00    -2.229551     2.229551  0.0500  0.0125 Power Family: alpha * t^phi
    
        2
  •  1
  •   Jannik Buhr    6 年前

    结果发现有人比我快(而且使用的代码行更少)。如果您对不需要手动插入列表名称的版本感兴趣,可以执行以下操作:

    library(ldbounds)
    library(tidyverse)
    example1 = bounds(t = c(.5,.75,1),iuse = c(3,3),alpha = c(0.025,0.025))
    example1 <- map(example1, `length<-`, max(lengths(example1)))
    example1 %>% as_data_frame() %>% fill(everything())
    

    首先,我用NAs填充列表中的所有向量,使其长度相同,然后我将它们组合到一个数据帧中,并在必要时用其上方行中的值替换NAs。 将长度赋值用作函数的一种奇怪、令人惊讶但相当优雅的方式来自于 this question