简体   繁体   中英

generate string of random letters and spaces in R

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"
...
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        "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM