[英]Sample from a list of data.frames
I have the following list1
and list2
: 我有以下list1
和list2
:
df1 <- data.frame(x=(1:3),Q=(3:5))
df2 <- data.frame(x=(1:3),Q=(3:5))
df3 <- data.frame(x=(1:3),Q=(3:5))
list1 <- list(df1,df2,df3)
list2 <- list(2,3,6)
I want to sample randomly from Q
in each list1
element according to the corresponding value in list2
我想根据list2
的对应值从每个list1
元素中的Q
中随机抽样
So I would sample from Q
2 times for the first pair of list elements. 所以我会从第2对Q
第一对列表元素中抽样。
So far I have managed: 到目前为止,我已经管理:
df1 <- data.frame(x=(1:3),Q=(3:5))
z <- 2
sapply(1:z,function(i) sample(df1$Q,1))
but I am struggling at trying to mapply
this across both all pairs of elements in both lists. 但我正在努力试图在两个列表中的所有元素对中进行mapply
。
这是一个mapply
方法:
mapply(function(x, y) sample(x[["Q"]], y, replace = TRUE), list1, list2)
Not sure if this is what you're after but it may help : 不确定这是否是您所追求的,但它可能会有所帮助:
FUN <- function(x, z) sapply(1:z,function(i) sample(x[["Q"]], 1))
lapply(seq_along(list1), function(i) FUN(list1[[i]], list2[[i]]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.