R 使用mapply或Lappy到嵌套列表
我想将示例函数应用于嵌套列表(我将此列表称为R 使用mapply或Lappy到嵌套列表,r,lapply,sampling,mapply,R,Lapply,Sampling,Mapply,我想将示例函数应用于嵌套列表(我将此列表称为bb),并且我还有一个数字列表(我将此列表称为k)将在示例函数中提供。我希望k中的每个数字都能遍历bb中每个列表的所有值。如何使用mappy或lappy执行此操作 以下是数据: 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
bb
),并且我还有一个数字列表(我将此列表称为k
)将在示例函数中提供。我希望k中的每个数字都能遍历bb中每个列表的所有值。如何使用mappy
或lappy
执行此操作
以下是数据:
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
这只返回10个输出值,但我希望每个k数循环通过
bb
中两个列表的所有值,因此bb
中的两个列表应有10*2个输出。我可能用错了mapply
,如果有人能给我指出正确的方向,我将不胜感激 outer
是你的朋友。它通常用于计算外矩阵积。考虑:
它还有一个FUN=
参数,默认为“*”
。但是,它允许您交叉计算x
和y
组合上的任何函数,即x[1]xy[1],x[1]xy[2],…
,而*apply
函数仅计算x[1]xy[1],x[2]xy[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
结果
瞧,20个结果。谢谢@jay.sf。实际上,
outer
是一个很少被寻找但非常有用的函数。正如您所说,mappy
函数同时在两个列表中循环,因此它确实耗尽了所有元素,即使我尝试了以下操作:Map(函数(I)mappy(函数(x,y){x[sample.int(y,y,replace=TRUE)],bb,k,SIMPLIFY=FALSE),seq_-along(bb))
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 <- 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
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