5
  1. I can create a sequence of single letters using

    LETTERS[seq( from = 1, to = 10 )]
    letters[seq( from = 1, to = 10 )]
    
  2. I can create a random string of various length, using the random package

    library(random)
    string <- randomStrings(n=10, len=5, digits=TRUE, upperalpha=TRUE,
                      loweralpha=TRUE, unique=TRUE, check=TRUE)
    

Unfortunately, I cannot use the set.seed function for example 2.

Is there a way to create the same (random) combination of (unique) strings everytime one runs a R-file?

My result would look like this (with the same result everytime I run the function):

       V1     
  [1,] "k7QET"
  [2,] "CLlWm"
  [3,] "yPuwh"
  [4,] "JJqEX"
  [5,] "38soF"
  [6,] "xkozk"
  [7,] "uaiOW"
  [8,] "tZcrW"
  [9,] "8K4Cc"
 [10,] "RAhuU"
rmuc8
  • 2,869
  • 7
  • 27
  • 36
  • @Richard Scriven I am looking for something like `set.seed(5) v1 <- runif(10, 0, 1)`. I always have the same numbers in the vector v1, but they are still random numbers – rmuc8 Mar 30 '15 at 11:21
  • I'm not sure if I have understood your question correctly. You want to have a vector of a series of random characters (strings) but you want them to be exactly the same every time you run the script? doesn't this somehow defeats the whole purpose of random generation? Anyway I guess you could store them just in a file and just load them every time. BTW upvoted because you helped m find the right answer to random string generation :) – Foad S. Farimani May 10 '18 at 22:03

2 Answers2

10

In a file, say test.R, add the following

set.seed(1)
stringi::stri_rand_strings(10, 5)

Then it's reproducible every time.

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"

As an alternative to source(), you could use parse() there.

replicate(5, eval(parse("test.R")))
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
  • exactly. thx. for my purpose, it would be sufficient to use `set.seed(1) stringi::stri_rand_strings(100, 5)` only – rmuc8 Mar 30 '15 at 11:27
8

An alternate solution in base R:

set.seed(1)
result <- rawToChar(as.raw(sample(c(65:90,97:122), 5, replace=T)))

Inspired by this answer to another post: https://stackoverflow.com/a/4370074/8297546

TuringTux
  • 559
  • 1
  • 12
  • 26
Derek Powell
  • 503
  • 5
  • 8