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.
Aucun commentaire:
Enregistrer un commentaire