在R中生成随机字母和空格的字符串

generate string of random letters and spaces in R

我正在尝试从随机选择的字母中生成随机单词字符串,并将它们与字符串的相似度进行比较。

使用 random 包,我可以轻松生成与我的字符串长度相同的随机字母序列,但是我想超越一个简单的单词并与一个句子进行比较。

为此,我的随机字符串生成需要包含 space 以创建单词,但我不确定如何包含 space 字符。

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)

输出:

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

期望的输出:

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