我可以使用
创建单个字母序列LETTERS[seq( from = 1, to = 10 )]
letters[seq( from = 1, to = 10 )]
我可以使用random
包
library(random)
string <- randomStrings(n=10, len=5, digits=TRUE, upperalpha=TRUE,
loweralpha=TRUE, unique=TRUE, check=TRUE)
不幸的是,我无法使用set.seed
函数,例如2
。
有没有办法在每次运行R文件时创建(唯一)字符串的相同(随机)组合?
我的结果看起来像这样(每次运行函数时都会得到相同的结果):
V1
[1,] "k7QET"
[2,] "CLlWm"
[3,] "yPuwh"
[4,] "JJqEX"
[5,] "38soF"
[6,] "xkozk"
[7,] "uaiOW"
[8,] "tZcrW"
[9,] "8K4Cc"
[10,] "RAhuU"
答案 0 :(得分:7)
在文件中,例如test.R,添加以下内容
set.seed(1)
stringi::stri_rand_strings(10, 5)
然后每次都可以重复。
replicate(5, source("test.R", verbose = FALSE)$value)
# [,1] [,2] [,3] [,4] [,5]
# [1,] "GNZuC" "GNZuC" "GNZuC" "GNZuC" "GNZuC"
# [2,] "twed3" "twed3" "twed3" "twed3" "twed3"
# [3,] "CAgNl" "CAgNl" "CAgNl" "CAgNl" "CAgNl"
# [4,] "UizNm" "UizNm" "UizNm" "UizNm" "UizNm"
# [5,] "vDe7G" "vDe7G" "vDe7G" "vDe7G" "vDe7G"
# [6,] "N0NrL" "N0NrL" "N0NrL" "N0NrL" "N0NrL"
# [7,] "TbUBp" "TbUBp" "TbUBp" "TbUBp" "TbUBp"
# [8,] "fn6iP" "fn6iP" "fn6iP" "fn6iP" "fn6iP"
# [9,] "oemYW" "oemYW" "oemYW" "oemYW" "oemYW"
# [10,] "m1Tjg" "m1Tjg" "m1Tjg" "m1Tjg" "m1Tjg"
作为source()
的替代方案,您可以在那里使用parse()
。
replicate(5, eval(parse("test.R")))
答案 1 :(得分:6)
基础R中的替代解决方案:
set.seed(1)
result <- rawToChar(as.raw(sample(c(65:90,97:122), 5, replace=T)))
受到另一篇文章的回答的启发:https://stackoverflow.com/a/4370074/8297546