Home > front end >  Sample from a 0:Vector[i]
Sample from a 0:Vector[i]

Time:10-19

In R:

I have a vector **

y = sample(0:200, 1e4, replace = TRUE)

I want to create a variable ‘x’ such that:

x = sample(0:y[i], 1e4, replace = TRUE)

Where y[i] are the values of y1, y2, …, y1e4 created from the sample function before. For example if y1 = 50 then I would like the first entry of x = sample(0:50) etc. However I am not sure how to do this. I have tried for loops but have gotten no where.

Any help is much appreciated!

CodePudding user response:

How about

x <- as.integer(runif(1e4)*sample(201, 1e4, TRUE))

Benchmarking:

f1 <- function() sapply(sample(0:200, 1e4, replace = TRUE), function(i) sample(0:i, size = 1))
f2 <- function() as.integer(runif(1e4)*sample(201, 1e4, TRUE))
microbenchmark::microbenchmark(f1 = f1(),
                               f2 = f2())
#> Unit: microseconds
#>  expr     min       lq      mean   median       uq     max neval
#>    f1 38877.3 47070.50 49294.770 48625.00 50175.35 97045.0   100
#>    f2   508.2   522.05   555.602   531.45   549.45  2080.8   100

CodePudding user response:

This should work:

y = sample(0:200, 1e4, replace = TRUE)
x = sapply(y, \(i) sample(0:i, size = 1)) 

Or the equivalent using a for loop:

x = numeric(length(y))
for(i in seq_along(y)) {
  x[i] = sample(0:y[i], size = 1)
}

If efficiency matters, this might be a bit faster on very long input:

x = floor(runif(length(y), min = 0, max = y   1))
  • Related