生成随机字符串 [英] Generating Random Strings

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

问题描述

我想通过以下方式生成随机字符串:ABCDE1234E,即每个字符串包含5个字符,4个数字和1个字符.

I want to generate random strings in the following way: ABCDE1234E, i.e each string contains 5 Characters, 4 Numerics, then 1 Char.

我想出了一种使用以下代码创建此代码的方法.

I figured out a way to create this using the following code.

library(random)
string_5 <- as.vector(randomStrings(n=5000, len=5, digits=FALSE, upperalpha=TRUE,
                        loweralpha=FALSE, unique=TRUE, check=TRUE))
number_4 <- as.vector(randomNumbers(n=5000, min=1111, max=9999, col=5, base=10, check=TRUE))
string_1 <- as.vector(randomStrings(n=5000, len=1, digits=FALSE, upperalpha=TRUE,
                         loweralpha=FALSE, unique=FALSE, check=TRUE))
PAN.Number <- paste(string_5,number_4,string_1,sep = "")

但是这些功能需要很长时间,并且random库需要网络连接.

But these functions are taking a long time and the random library needs a network connection.

> system.time(string_5 <- as.vector(randomStrings(n=5000, len=5, digits=FALSE, upperalpha=TRUE,
+                                                 loweralpha=FALSE, unique=TRUE, check=TRUE)))
   user  system elapsed 
   0.07    0.00    3.18 

是否可以尝试减少执行时间的任何方法? 我也尝试使用sample(),但无法弄清楚.

Is there any method that I could try to reduce the execution time? I also tried using sample() but I couldn't figure it out.

推荐答案

使用@akrun建议的"stringi"会更快,但是以下操作也非常快,不需要任何其他软件包:

Using "stringi" as suggested by @akrun will be faster, but the following is also very fast and does not require any additional packages:

myFun <- function(n = 5000) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

示例输出:

myFun(10)
##  [1] "BZHOF3737P" "EPOWI0674X" "YYWEB2825M" "HQIXJ5187K" "IYIMB2578R"
##  [6] "YSGBG6609I" "OBLBL6409Q" "PUMAL5632D" "ABRAT4481L" "FNVEN7870Q"

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

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