我想在向量列表上迭代一个函数。我正在尝试使用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
[如果我理解正确,请对每个exampleList [[i]]进行lapply迭代,因此不需要指定'v'参数(请注意,尝试指定它时仍然会出错)。是什么导致我的结果不一致?
[尝试将n
和r
的值设为length(exampleList)
。但是,它应等于列表中每个单独元素的长度。
lapply(exampleList, function(x)
gtools::permutations(n = length(x), r = length(x), v = x))
#[[1]]
# [,1] [,2]
#[1,] "COMBINATIONS" "RETURN"
#[2,] "RETURN" "COMBINATIONS"
#[[2]]
# [,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
#[[3]]
# [,1]
#[1,] "PLEASE WORK"
您也可以用Map
编写此内容
Map(function(x, y) gtools::permutations(n = y, r = y, v = x),
exampleList, lengths(exampleList))