I have an object with 37 elements.
I want to randomly select from the object different number of elements and assign them to different objects without replacement. How can I do that?
vars <- c("a1", "b2", "c3", "d4", "e5", "f6", "g7", "h8", "i9", "j10", "k11", "l12", "m13", "n14", "o15",
"p16", "q17", "r18", "s19", "t20", "u21", "v22", "w23", "x24", "y25", "z26", "a27", "b28", "c29", "d30",
"e31", "f32", "g33", "h34", "i35", "j36", "k37")
Group1 = 4 elements randomly selected from vars
Group2 = 5 elements randomly selected from vars
Group3 = 6 elements randomly selected from vars
Group4 = 9 elements randomly selected from vars
Group5 = 6 elements randomly selected from vars
Group6 = 7 elements randomly selected from vars
CodePudding user response:
You may try
split(vars, sample(rep(paste0("Group", 1:6), c(4, 5, 6, 9, 6, 7))))
$Group1
[1] "f6" "i9" "b28" "d30"
$Group2
[1] "c3" "d4" "j10" "p16" "r18"
$Group3
[1] "h8" "k11" "m13" "s19" "w23" "k37"
$Group4
[1] "e5" "g7" "u21" "z26" "a27" "c29" "e31" "i35" "j36"
$Group5
[1] "l12" "q17" "t20" "v22" "f32" "h34"
$Group6
[1] "a1" "b2" "n14" "o15" "x24" "y25" "g33"
CodePudding user response:
The function sample
should do it.
Group1<-sample(vars,4)
Group2<-sample(vars,5)
Just type in the number of elements you want to be sampled and it will select them.
Fair note to add is that it won't be truly random but pseudo-random depending upon a pre-generated seed. If you set the seed for rng then you can reproduce the random samples every time.
For eg, set.seed(341); sample(vars, 6)
. You may not need to set the seed in which case you will be able to sample different elements every time