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))
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"
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 = ''))
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