Home > OS >  Randomly distribute a set of string into a vector
Randomly distribute a set of string into a vector

Time:07-03

Is there any function that randomly distributes a specific set of strings into a vector form? As an example,

Str <- c('A','B','C','D','E')

and I want to make Str100 which contains 100 randomly distributed variables from Str, like ('A','B','A','D','C','E', .......... ). What function is needed for this?

Also, is it possible to make it with same number of each variables in Str, like 20 'A' and 20 'B' etc.

CodePudding user response:

Str <- c('A', 'B', 'C', 'D', 'E')

I want to make Str100 which contains 100 randomly distributed variables from Str.

sample(Str, size = 100, replace = TRUE)

Also, is it possible to make it with same number of each variables in Str.

## the outside `sample` is used to produce a random shuffle
sample(rep(Str, each = 20), replace = FALSE)

Read documentation ?sample and ?rep to learn more about these functions.

  •  Tags:  
  • r
  • Related