virgin technician
virgin technician

Reputation: 33

Randomly distribute a set of string into a vector

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.

Upvotes: 1

Views: 46

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73325

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.

Upvotes: 2

Related Questions