在 R 中生成多个字符的(随机)序列 [英] Generating a (random) sequence of multiple characters in R

查看:48
本文介绍了在 R 中生成多个字符的(随机)序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我可以使用

  1. I can create a sequence of single letters using

LETTERS[seq( from = 1, to = 10 )]
letters[seq( from = 1, to = 10 )]

  • 我可以使用 random 包创建一个不同长度的随机字符串

  • 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)
    

  • 不幸的是,我不能使用 set.seed 函数,例如 2.

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

    有没有办法在每次运行 R 文件时创建(唯一)字符串的相同(随机)组合?

    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"
    

    推荐答案

    在一个文件中,比如 test.R,添加以下内容

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

    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().

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

    replicate(5, eval(parse("test.R")))
    

    这篇关于在 R 中生成多个字符的(随机)序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆