【发布时间】:2021-05-23 04:59:33
【问题描述】:
我正在尝试从嵌套在lapply 中的mapply 产生的复杂列表中提取数据。
目的是生成具有不同输入组合的模型模拟。
如果有帮助,请查看其他帖子:How to use mapply with sets of inputs of unequal lengths, using combinations of arguments?。
输出是一个如下所示的列表:
> output
[[1]]
[,1] [,2] [,3]
Variable1 Numeric,2 Numeric,5 Numeric,7
Variable2 Integer,2 Integer,5 Integer,7
[[2]]
[,1] [,2] [,3]
Variable1 Numeric,2 Numeric,5 Numeric,7
Variable2 Integer,2 Integer,5 Integer,7
...
此结构在列表中重复 n 次,与 lapply 请求的次数一样多。
我想从每个元素([[1]]、[[2]]、@987654332 @ 等)。
理想情况下,输出将是一个长格式的数据帧,列表级别和变量名称伴随着提取的值:
List_index Column Last_value_Variable1
[[1]] [,1] 5
[[1]] [,2] 2
[[1]] [,3] 7
[[2]] [,1] 8
[[2]] [,2] 1
[[2]] [,3] 9
... ... ...
如果需要,可以重命名列表索引和变量名。 我不确定我正在处理什么样的对象(一个列表,但是里面的嵌套列表......,而且有点不同......)。 我知道如何手动访问较低级别的最后一个元素(代码如下),但不知道如何迭代流程。
> output[[1]][,1]$Variable1[-1]
5
> output[[2]][,3]$Variable1[-1]
9
在output 上使用dput 会返回类似这样的内容(简化,因为实际的内容太长):
structure(list(
c(1, 2), c(80L, 80L), c(2.2, 20.3),
c(1, 2, 3, 4, 5), c(62L, 62L, 62L, 62L, 62L), c(1.7, 15.9, 24.4, 30.5, 35.2),
c(1, 2, 3, 4, 5, 6, 7), c(25L, 25L, 25L, 25L, 25L, 25L, 25L), c(1.7, 15.9, 24.4, 30.5, 35.2, 39.1, 42.4)),
#[rest of the list removed for clarity because it's too long]
.Dim = c(16L, 11L),
.Dimnames = list(c("Variable1", "Variable2", "Variable3", "Variable4", "Variable5", "Variable6", "Variable7", "Variable8", "Variable9", "Variable10", "Variable11", "Variable12", "Variable13", "Variable14", "Variable15", "Variable16"),
NULL))
模型是一个函数,它返回一个数据框,其中包含 16 个变量和与模型输入之一相对应的可变数量的观察值。该模型使用一组 11 个参数输入进行了测试(因此在上面的 dput() 中使用了 .Dim = c(16L, 11L))。
我需要针对不同输入的组合运行模拟。
列表的第一级 ([[i]]) 对应于一个参数输入范围(馈入lapply 函数),第二级 ([,j]) 对应于馈入mapply 函数的另一组参数(在本例中为 11)。
【问题讨论】:
-
你能提供一个
dput()的数据示例吗?它使写答案变得容易得多。 -
很遗憾,当我尝试创建您的对象时出现错误
Error in attributes(.Data) <- c(attributes(.Data), attrib) : dims [product 176] do not match the length of object [9] -
tidyr 包中的
unnest_longer()可能在这里会很有帮助。
标签: r list loops nested iteration