【问题标题】:Use mapply or lapply to nested list使用 mapply 或 lapply 到嵌套列表
【发布时间】:2021-03-31 12:00:40
【问题描述】:

我想将示例函数应用于嵌套列表(我将调用此列表bb),并且我还有一个要在示例函数中提供的数字列表(我将调用此列表k)。我希望 k 中的每个数字都遍历 bb 中每个列表的所有值。如何使用mapplylapply 做到这一点?

以下是数据:

k <- list(1,2,4,3) #this is the list of numbers to be supplied in the `sample.int` function
b1 <- list(c(1,2,3),c(2,3,4),c(3,4,5),c(4,5,6)) #The first list of bb
b2 <- list(c(1,2),c(2,3),c(3,4),c(4,5), c(5,6)) #The second list of bb
bb <- list(b1,b2) #This is list bb containing b1 and b2 whose values are to be iterated through

我创建了这个mapply 函数,但没有得到预期的结果:

mapply(function(x, y) { 
   x[sample.int(y,y, replace = TRUE)] 
}, bb,k, SIMPLIFY = FALSE)

这仅返回 10 个输出值,但我希望每个 k 数循环遍历 bb 中两个列表的所有值,因此 bb 中的两个列表应该有 10*2 个输出。我可能以错误的方式使用mapply,所以如果有人能指出我正确的方向,我将不胜感激!

【问题讨论】:

    标签: r lapply sampling mapply


    【解决方案1】:

    outer 是你的朋友。它通常用于计算外矩阵乘积。 考虑:

    outer(1:3, 2:4)
    1:3 %o% 2:4  ## or
    #      [,1] [,2] [,3]
    # [1,]    2    3    4
    # [2,]    4    6    8
    # [3,]    6    9   12
    

    它还有一个FUN= 参数,默认为"*"。但是,它使您能够计算 xy cross-wise 组合的任何函数,即 x[1] X y[1], x[1] X y[2], ...*apply 函数仅计算 x[1] X y[1], x[2] X y[2], ...。所以让我们开始吧:

    FUN <- Vectorize(function(x, y) x[sample.int(y, y)])
    
    set.seed(42)
    res <- outer(bb, k, FUN)
    res
    #        [,1]   [,2]   [,3]   [,4]  
    # [1,] List,1 List,2 List,4 List,3
    # [2,] List,1 List,2 List,4 List,3
    

    这个结果看起来有点奇怪,但我们可以很容易地unlist它。

    res <- unlist(res, recursive=F)
    

    结果

    res
    # [[1]]
    # [1] 1 2 3
    # 
    # [[2]]
    # [1] 1 2
    # 
    # [[3]]
    # [1] 1 2 3
    # 
    # [[4]]
    # [1] 2 3 4
    # 
    # [[5]]
    # [1] 2 3
    # 
    # [[6]]
    # [1] 1 2
    # 
    # [[7]]
    # [1] 2 3 4
    # 
    # [[8]]
    # [1] 4 5 6
    # 
    # [[9]]
    # [1] 1 2 3
    # 
    # [[10]]
    # [1] 3 4 5
    # 
    # [[11]]
    # [1] 3 4
    # 
    # [[12]]
    # [1] 4 5
    # 
    # [[13]]
    # [1] 2 3
    # 
    # [[14]]
    # [1] 1 2
    # 
    # [[15]]
    # [1] 1 2 3
    # 
    # [[16]]
    # [1] 2 3 4
    # 
    # [[17]]
    # [1] 3 4 5
    # 
    # [[18]]
    # [1] 2 3
    # 
    # [[19]]
    # [1] 3 4
    # 
    # [[20]]
    # [1] 1 2
    

    瞧,20 个结果。

    【讨论】:

    • 谢谢@jay.sf。事实上outer 是一个很少被寻求但非常有用的功能。就像你说的那样,mapply 函数同时遍历两个列表,因此它确实耗尽了所有元素,即使我尝试了这个:Map(function(i) mapply(function(x, y) { x[sample.int(y,y, replace = TRUE)] }, bb,k, SIMPLIFY = FALSE), seq_along(bb))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2020-02-24
    • 2021-10-30
    • 2014-01-21
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多