【发布时间】:2020-10-14 12:13:12
【问题描述】:
抱歉,如果这已经在某处得到解答,但我检查了所有我能找到的页面,但找不到解决这个特定问题的方法。
我想使用 apply 函数从嵌套在列表中的列表中选择元素。我想从子列表中选择的元素因单独列表中包含的参数而异。这是一些示例代码来说明我正在尝试做的事情:
# Set seed for replicable results
set.seed(123)
# Create list of lists populated with randomly generated numbers
list1 <- list()
for (i in 1:10) {
list1[[i]] <- as.list(sample.int(20, 10))
}
# Create second randomly generated list
list2 <- as.list(sample.int(10, 10))
# For loop with uses values from list 2 to call specific elements from sub-lists within list1
for (i in 1:10){
print(list1[[i]][[list2[[i]]]])
}
####################################################################################
[1] 4
[1] 8
[1] 5
[1] 8
[1] 15
[1] 17
[1] 12
[1] 15
[1] 3
[1] 15
如您所见,我可以使用 for 循环成功地从嵌套在 list1 中的子列表中选择元素,使用来自 list2 的值并结合迭代值 i。
为此类问题提供的解决方案 (R apply function with multiple parameters) 表明我应该能够使用 mapply 函数实现相同的结果。但是,当我尝试这样做时,出现以下错误:
# Attempt to replicate output using mapply
mapply(function(x,y,z) x <- x[[z]][[y[[z]]]], x=list1, y=list2, z=1:10 )
####################################################################################
Error in x[[z]][[y[[z]]]] : subscript out of bounds
我的问题是:
-
如何更改我的代码以达到预期的结果?
-
是什么导致了这个错误?过去,当我尝试在向量旁边输入一个或多个列表时,我在使用 mapply 时遇到过类似的问题,但一直无法弄清楚为什么它有时会失败。
非常感谢!
【问题讨论】:
标签: r nested-lists mapply