【发布时间】:2020-01-10 00:19:23
【问题描述】:
我想在向量列表上迭代一个函数。我正在尝试使用 Lapply,但这会产生不需要的结果,而具有相同参数的 for 循环具有正确的结果:
可重现的例子:
library(gtools) # for 'permutations' function
exampleList <- list(c("RETURN", "COMBINATIONS"), c(1,2,3), c("PLEASE WORK") )
期望的输出(for循环返回的内容):
for (i in 1:length(exampleList)) {
print( permutations(n = length(exampleList[[i]]), r = length(exampleList[[i]]), v = exampleList[[i]]))
}
[,1] [,2]
[1,] "COMBINATIONS" "RETURN"
[2,] "RETURN" "COMBINATIONS"
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 3 2
[3,] 2 1 3
[4,] 2 3 1
[5,] 3 1 2
[6,] 3 2 1
[,1]
[1,] "PLEASE WORK"
Lapply 版本当前返回的内容:
lapply(exampleList, permutations, n = length(exampleList), r = length(exampleList))
Error in FUN(X[[i]], ...) : v is either non-atomic or too short
如果我理解正确,lapply 会遍历每个 exampleList[[i]],因此不需要指定 'v' 参数(请注意,我在尝试指定它时仍然会出错)。是什么导致我的结果不一致?
【问题讨论】:
标签: r for-loop permutation lapply