I want to choose elements randomly in character vector in R.
For example, I have character vector including 36 alphabets.
f <- c('A', 'B', 'C', 'D', 'E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','f','g','h','i','j','k')
I want to make random sampling in this character vector. What I want to make as a result is like below.
[,1] [,2] [,3]
[1,] "a" "B" "C"
[2,] "D" "E" "F"
[3,] "H" "I" "J"
[4,] "K" "L" "M"
...
[12,] "Z" "c" "m"
The point is that I want to randomly select alphabets without replacement, and make matrix like above using chosen alphabets
i <- 1
a <- matrix(0,12,3)
for(i in 1:12){
a_temp <- sample(f,3)
while(any(a_temp==a)){
idx <- which(f %in% a_temp)
f <- f[-idx]
a_temp <- sample(f,3)
}
a[i,] <- a_temp
i+1
}
> a
[,1] [,2] [,3]
[1,] "D" "A" "G"
[2,] "S" "f" "W"
[3,] "M" "Q" "O"
[4,] "M" "D" "U"
[5,] "K" "C" "F"
[6,] "E" "O" "b"
[7,] "h" "V" "c"
[8,] "N" "j" "k"
[9,] "j" "a" "R"
[10,] "B" "H" "f"
[11,] "L" "i" "A"
[12,] "E" "R" "X"
However, I could only get the matrix which include duplicated alphabet.
(What I mean is that I want to make all of alphabets have eqaul opportunity to be chosen only once)
You only need to sample once:
f <- c('A', 'B', 'C', 'D', 'E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','f','g','h','i','j','k')
a <- matrix(sample(f),12,3)
a
[,1] [,2] [,3]
[1,] "U" "P" "a"
[2,] "Z" "f" "B"
[3,] "b" "I" "N"
[4,] "k" "M" "c"
[5,] "V" "Y" "E"
[6,] "F" "K" "D"
[7,] "L" "O" "X"
[8,] "J" "A" "H"
[9,] "g" "R" "d"
[10,] "i" "j" "G"
[11,] "S" "Q" "T"
[12,] "C" "h" "W"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With