Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I randomly choosing elements in character vector in R?

Tags:

r

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)

like image 669
ygy526 Avatar asked Dec 24 '22 12:12

ygy526


1 Answers

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" 
like image 164
drJones Avatar answered Mar 09 '23 00:03

drJones