Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sample from a list of data.frames

Tags:

list

r

I have the following list1 and 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

So I would sample from Q 2 times for the first pair of list elements.

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.

like image 615
user1322296 Avatar asked Aug 04 '26 09:08

user1322296


1 Answers

Here's a mapply approach:

mapply(function(x, y) sample(x[["Q"]], y, replace = TRUE), list1, list2)
like image 123
Sven Hohenstein Avatar answered Aug 07 '26 00:08

Sven Hohenstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!