【问题标题】:For-loop and Lapply: Same function gives different resultsFor-loop 和 Lapply:相同的函数给出不同的结果
【发布时间】: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


    【解决方案1】:

    在您的尝试中,您将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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多