Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - shuffle a list preserving element sizes

Tags:

list

r

In R, I need an efficient solution to shuffle the elements contained within a list, preserving the total number of elements, and the local element sizes (in this case, each element of the list is a vector)

a<-LETTERS[1:6]
b<-LETTERS[6:10]
c<-LETTERS[c(9:15)]

l=list(a,b,c)
> l
[[1]]
[1] "A" "B" "C" "D" "E" "F"

[[2]]
[1] "F" "G" "H" "I" "J"

[[3]]
[1] "I" "J" "K" "L" "M" "N" "O"

The shuffling should randomly select the letters of the list (without replacement) and put them in a random position of any vector within the list.

I hope I have been clear! Thanks :-)

like image 324
Thrawn Avatar asked Dec 11 '22 12:12

Thrawn


2 Answers

you may try recreating a second list with the skeleton of the first, and fill it with all the elements of the first list, like this:

u<-unlist(l)
l2<-relist(u[sample(length(u))],skeleton=l)
> l2
[[1]]
[1] "F" "A" "O" "I" "S" "Q"

[[2]]
[1] "R" "P" "K" "F" "G"

[[3]]
 [1] "A" "N" "M" "J" "H" "G" "E" "B" "T" "C" "D" "L"

Hope this helps!

like image 129
Federico Giorgi Avatar answered Jan 03 '23 10:01

Federico Giorgi


Like this...?

> set.seed(1)
> lapply(l, sample)
[[1]]
[1] "B" "F" "C" "D" "A" "E"

[[2]]
[1] "J" "H" "G" "F" "I"

[[3]]
[1] "J" "M" "O" "L" "N" "K" "I"
like image 43
Jilber Urbina Avatar answered Jan 03 '23 11:01

Jilber Urbina