简体   繁体   中英

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.

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.

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
  • randomly pick len numbers from [0, 9]
  • 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.

Doesn't that boil down to generating a random number between 100 and 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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