Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a (random) sequence of multiple characters in R

Tags:

random

r

  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"
like image 894
rmuc8 Avatar asked Dec 04 '22 04:12

rmuc8


1 Answers

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")))
like image 149
Rich Scriven Avatar answered Jan 17 '23 15:01

Rich Scriven