简体   繁体   English

在R中生成3到7位的随机数

[英]Generate random numbers with 3 to 7 digits in R

How can I generate random numbers of varying length, say between 3 to 7 digits with equal probability. 如何生成不同长度的随机数,比如说3到7位数的概率相等。

At the end I would like the code to come up with a 3 to 7 digit number (with equal probability) consisting of random numbers between 0 and 9. 最后,我希望代码能够得到一个3到7位数字(概率相等),由0到9之间的随机数组成。

I came up with this solution but feel that it is overly complicated because of the obligatory generation of a data frame. 我提出了这个解决方案但觉得它过于复杂,因为必须生成一个数据框。

options(scipen=999)
t <- as.data.frame(c(1000,10000,100000,1000000,10000000))
round(runif(1, 0,1) * sample_n(t,1, replace = TRUE),0)

Is there a more elegant solution? 有更优雅的解决方案吗?

Based on the information you provided, I came up with another solution that might be closer to what you want. 根据您提供的信息,我想出了另一种可能更接近您想要的解决方案。 In the end, it consists of these steps: 最后,它包括以下步骤:

  • randomly pick a number len from [3, 7] determining the length of the output 从[ len ]中随机选取一个数字len来确定输出的长度
  • randomly pick len numbers from [0, 9] 随机从[ len ]中选择len数字
  • concatenate those numbers 连接这些数字

Code to do that: 代码来做到这一点:

(len <- runif(1, 3, 7) %/% 1)
(s <- runif(len, 0, 9) %/% 1)
cat(s, sep = "")

I previously provided this answer; 我之前提供了这个答案; it does not meet the requirements though, as became clear after OP provided further details. 但是,它不符合要求,因为OP提供了进一步的细节后变得清晰。

Doesn't that boil down to generating a random number between 100 and 9999999? 不能归结为生成100到9999999之间的随机数吗? If so, does this do what you want? 如果是这样,这会做你想要的吗?

runif(5, 100, 9999999) %/% 1

You could probably also use round, but you'd always have to round down. 你可能也可以使用round,但你总是要向下舍入。

Output: 输出:

[1] 4531543 9411580 2195906 3510185 1129009

You could use a vectorized approach, and sample from the allowed range of exponents directly in the exponent: 您可以使用向量化方法,并直接在指数中从允许的指数范围中进行采样:

pick.nums <- function(n){floor(10^(sample(3:7,n,replace = TRUE))*runif(n))}

For example, 例如,

> set.seed(123)
> pick.nums(5)
[1]     455  528105   89241 5514350 4566147

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM