Search code examples
rrandomnested-listssample

sample 1 element from each list in nested list in R to create groups of samples


I have a nested list of lists where each entry contains a list of values.

I wish to sample a single element from each nested list and create a group of elements.

An example of such a list is:

xxx_ <- list(c(13L, 15L, 5L, 6L), c(7L, 20L, 14L, 18L, 1L, 8L, 17L), 
    c(9L, 11L, 4L, 12L), c(16L, 19L, 10L, 2L, 3L))

I was doing the following, but it feel like there need to be a simpler way of sampling this list of lists.

l_sample <- list()
for(g in 1:10) {
  l <- c()
  for(i in 1:4) {
    l <- c(l,sample(xxx_[[i]], 1))
  }
  l_sample[[g]] <- l
}

Which gives the following result:

> l_sample
[[1]]
[1] 15  7 12 10

[[2]]
[1] 6 1 4 2

[[3]]
[1] 13 18  4 19

[[4]]
[1]  6 17  4  2

[[5]]
[1] 15 18  4  3

[[6]]
[1] 13 18  9  3

[[7]]
[1]  6 17 12 19

[[8]]
[1]  5 20  9 19

[[9]]
[1]  5 18  9 10

[[10]]
[1] 13  7  9  3

I also wanted to append each sample to data-frame as new row, where each element is in new column, but I couldn't do it.

something like:

> df
  g1 g2 g3 g4
1 15  7 12 10
2 6 1 4 2
...

Would appreciate some help.


Solution

  • You could use sapply to select 1 element from each list and use replicate to repeat it 10 times.

    t(replicate(10, sapply(xxx_, sample, 1)))
    
    #      [,1] [,2] [,3] [,4]
    # [1,]   15    7    9   10
    # [2,]   15    8    9    3
    # [3,]   13   14    4   19
    # [4,]    5   14   12   10
    # [5,]   13   20    9    3
    # [6,]    5   18   12   16
    # [7,]    5    1   11    2
    # [8,]    6   14   11   19
    # [9,]    5    8   12    3
    #[10,]    5   17    4    2