0
$\begingroup$

In R, I need to make 100 repeat random permutations of group orders, keeping the composition and sizes of groups the same, but the order within the groups needs to be randomly shuffled (100 times)

By groups are A, B, C, D, E

For example,

A, B, B, B, E

A, E, E, C

C, E

C, D, D, A, A, E, C, E

C, D 

D, E 

Might become

B, B, E, B, A

A, C, E, E

E, C

D, A, A, C, E, D, E

D, C

E, D 

shuffled 100 different ways as an output?

$\endgroup$

1 Answer 1

1
$\begingroup$

lapply() together with sample() work:

groups <- list(
    c("A","B","B","B","E"),
    c("A","E","E","C"),
    c("C","E"),
    c("C","D","D","A","A","E","C","E"),
    c("C","D"),
    c("D","E"))

lapply(groups,function(xx)sample(xx,size=length(xx)))

[[1]]
[1] "E" "B" "A" "B" "B"

[[2]]
[1] "E" "C" "A" "E"

[[3]]
[1] "E" "C"

[[4]]
[1] "C" "E" "A" "E" "D" "D" "C" "A"

[[5]]
[1] "C" "D"

[[6]]
[1] "D" "E"
$\endgroup$
2
  • $\begingroup$ thank you, this makes sense and is very helpful. And would I use a for loop to generate this 100 times? for (i in 1:100) { lapply(groups,function(xx)sample(xx,size=length(xx))) } - how is this saved as an output? $\endgroup$
    – Becca
    Commented Feb 20, 2019 at 13:53
  • $\begingroup$ It depends on what you want to do with it. You can save the 100 permutations in a list of lists. Or you can calculate the statistic you are interested in (assuming you are doing this for a permutation test), and then just save the resulting statistics in a vector of length 100. $\endgroup$ Commented Feb 20, 2019 at 13:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.