在R中,我需要一个有效的解决方案来重新排列列表中包含的元素,保留元素的总数和本地元素大小(在这种情况下,列表的每个元素都是一个向量)
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"
改组应随机选择列表中的字母(不替换),并将它们放在列表中任何向量的随机位置。
我希望我已经清楚了!谢谢: - )
答案 0 :(得分:10)
您可以尝试使用第一个列表的骨架重新创建第二个列表,并将其填入第一个列表的所有元素,如下所示:
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"
希望这有帮助!
答案 1 :(得分:3)
喜欢这个......?
> 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"