【问题标题】:Extract a variable from a nested list in r从 r 中的嵌套列表中提取变量
【发布时间】:2021-12-29 23:15:33
【问题描述】:

我有一个以列表形式返回输出的函数,如下所示。我只想从中提取变量“值”。

output
             [,1]   [,2]  
weights_used List,4 List,6
value        3      1  

我可以单独提取值,比如说

output[,1]$value
[1] 3

output[,2]$value
[1] 1

如何将上面的值 3 和 1 一起提取到一个新列表中? (我的实际输出会有更多的值)。如果我尝试 output["value"] 或 output[["value"]],它们会产生 NULL

我也无法理解为什么变量名“value”会从 unlist(output) 中消失..

> unlist(output)
  weight1   weight2   weight3   weight4             weight1   weight2   weight3   weight4   weight5   weight6           
0.1666667 0.1666667 0.1666667 0.5000000 3.0000000 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 1.0000000

谢谢!

> dput(output)
structure(list(list(weight1 = 0.166666666666667, weight2 = 0.166666666666667, 
    weight3 = 0.166666666666667, weight4 = 0.5), 3, list(weight1 = 0.166666666666667, 
    weight2 = 0.166666666666667, weight3 = 0.166666666666667, 
    weight4 = 0.166666666666667, weight5 = 0.166666666666667, 
    weight6 = 0.166666666666667), 1), .Dim = c(2L, 2L), .Dimnames = list(
    c("weights_used", "value"), NULL))

【问题讨论】:

标签: r list


【解决方案1】:

对我有用的方法如下所示.. 但我相信还有更优雅的方法!

unlisted.output <- unlist(output)
as.list(unlisted.output[names(unlisted.output) == ""])

【讨论】:

    【解决方案2】:

    只需按照矩阵格式并选择名称为'value' 的行。

    output['value', ]
    # [[1]]
    # [1] 3
    # 
    # [[2]]
    # [1] 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2021-03-06
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多