Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

5 letters "word" randomly generated

I would like to create a vector of 10 "words" made of 5 characters that have been randomly generated. e.g c("ASDT","WUIW"...)

At the moment I am using the following script but surely there should be a much better way of doing this

result = list()
for (i in 1:10){
result[i]<-paste(sample(LETTERS, 5, replace=TRUE),collapse="")
}
result<-paste(t(result))
like image 982
ulrich Avatar asked Feb 23 '15 13:02

ulrich


2 Answers

I would sample once and turn the result into a data.frame, which can be passed to paste0:

set.seed(42)
do.call(paste0, as.data.frame(matrix(sample(LETTERS, 50, TRUE), ncol = 5)))
#[1] "XLXTJ" "YSDVL" "HYZKA" "VGYRZ" "QMCAL" "NYNVY" "TZKAX" "DDXFQ" "RMLXZ" "SOVPQ"
like image 119
Roland Avatar answered Oct 13 '22 07:10

Roland


There’s nothing fundamentally wrong with your code, except maybe for the fact that it’s using a loop.

The only better way is to replace the loop with a list application function (in this case: replicate):

replicate(10, paste(sample(LETTERS, 5, replace = TRUE), collapse = ''))
like image 6
Konrad Rudolph Avatar answered Oct 13 '22 07:10

Konrad Rudolph