Search code examples
rrandomsample

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?


Solution

  • 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