5 letters "word" randomly generated

I would like to create a 10-word vector consisting of 5 characters that were randomly generated. e.g. c ("ASDT", "WUIW" ...)

I am currently using the following script, but there certainly should be a much better way to do this

result = list() for (i in 1:10){ result[i]<-paste(sample(LETTERS, 5, replace=TRUE),collapse="") } result<-paste(t(result)) 
+6
source share
4 answers

I would try once and turn the result into a data.frame file, 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" 
+6
source

There is nothing fundamentally wrong with your code, except perhaps because it uses a loop.

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

 replicate(10, paste(sample(LETTERS, 5, replace = TRUE), collapse = '')) 
+6
source

I would create a custom function such as this that will take the size of the word and the number of words you want in response

 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" 
+4
source

Here is an option from stringi

 library(stringi) set.seed(1) stri_rand_strings(10, 5, '[AZ]') #[1] "GJOXF" "XYRQB" "FERJU" "MSZJU" "YFQDG" "KAJWI" "MPMEV" "RUCSK" "VQUON" #[10] "UAMTS" 
+4
source

Source: https://habr.com/ru/post/982891/


All Articles