Reputation: 3587
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))
Upvotes: 6
Views: 530
Reputation: 887223
Here is an option from stringi
library(stringi)
set.seed(1)
stri_rand_strings(10, 5, '[A-Z]')
#[1] "GJOXF" "XYRQB" "FERJU" "MSZJU" "YFQDG" "KAJWI" "MPMEV" "RUCSK" "VQUON"
#[10] "UAMTS"
Upvotes: 5
Reputation: 92292
I would create a custom function such as this one which will accept the size of a word and the number of words you want in return
WordsGen <- function(n, size){
substring(paste(sample(LETTERS, n * size, replace = TRUE), collapse = ""),
seq(1, (n - 1)*size + 1, size), seq(size, n * size, size))
}
set.seed(1)
WordsGen(10, 5)
## [1] "GJOXF" "XYRQB" "FERJU" "MSZJU" "YFQDG" "KAJWI" "MPMEV" "RUCSK" "VQUON" "UAMTS"
Upvotes: 4
Reputation: 132706
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"
Upvotes: 6
Reputation: 545628
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 = ''))
Upvotes: 6