Home > Mobile >  generate string of random letters and spaces in R
generate string of random letters and spaces in R

Time:05-19

I am trying to generate random strings of words from randomly selected letters and compare their similarity to a string.

Using the random package, I can easily generate random sequences of letters of the same length as my string, however I want to go beyond a simple word and compare against a sentence.

To do that, my random string generation needs to include spaces so as to create words, but I am not sure how to include the space character.

library(random)

text = 'THIS IS A DEMO'
textlength <- nchar(text)

string <- randomStrings(
    n = 100, 
    len = textlength, 
    digits = FALSE, 
    upperalpha = TRUE,
    loweralpha = FALSE, 
    unique = FALSE, 
    check = TRUE)

output:

[1,] "QSBMNCORYVYPVB"
[2,] "WCGGPWLPYLAIIH"
...

desired output:

[1,] "QSB MNC R YV  "
[2,] "W G  PWLP  IIH"
...

CodePudding user response:

text = 'THIS IS A DEMO'
textlength <- nchar(text)

n <- 10

string <- random::randomStrings(
  n = n, 
  len = textlength, 
  digits = FALSE, 
  upperalpha = TRUE,
  loweralpha = FALSE, 
  unique = FALSE, 
  check = TRUE)

spaces <- replicate(n, 
        structure(sort(sample(textlength, sample(textlength, 1))),
                      match.length = 1))

regmatches(string, spaces) <- " "
string

 [1] " A  Z         " "W  YL JSJI FYV" "LL  D  AG     " "  XH Z   FV R "
 [5] "    B    Y F  " "AHO QDZOM ADLQ" " REKOEQMNG H J" "O D    FWO  P "
 [9] "       B S    " "     A        "
  • Related