使用 mapply 或 lapply 嵌套列表

Use mapply or lapply to nested list

我想将示例函数应用于嵌套列表(我将调用此列表 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)

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

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 交叉 组合的任何函数,即 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 个结果。