[R] Use mapply or lapply to a nested list

Chao Liu p@ych@o||u @end|ng |rom gm@||@com
Mon Dec 21 20:35:23 CET 2020

I want to apply a sample function to a nested list (I will call this list
`bb`) and I also have a list of numbers (I will call this list `k`) to be
supplied in the sample function. I would like each of the numbers in k to
iterate through all the values of each list in bb. How to do this using
`mapply` or `lapply`?

Here are the data:
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
I created this `mapply` function but it didn't get the expected outcome:
mapply(function(x, y) {
   x[sample.int(y,y, replace = TRUE)]
}, bb,k, SIMPLIFY = FALSE)
This only returns 10 output values but I would like each number of k to
loop through all values of the two lists in `bb` and so there should be
10*2 outputs for the two lists in `bb`. I might be using `mapply` in the
wrong way and so I would appreciate if anyone can point me to the right


	[[alternative HTML version deleted]]

More information about the R-help mailing list