简体   繁体   中英

Resampling the sampled vector multiple times in R

Let's say I have a vector y of length 100. I want to sample 95 values from y without replacement and take the mean of that sample. Then, from the new vector, I want to sample 90 values and take the mean of that vector. I want to do this 20 times. In the end, my result should be a vector of length 20, each of which is a mean of a sample.

I am thinking a for loop would work for this but I can't seem to figure it out.

ss = seq(from = 95, to = 20, by = -5)
r = length(ss)
i = 1
x = rnorm(100)
for(sampSize in ss){
  x = sample(x, size = sampSize)
  r[i] = mean(x)
  i = i + 1
}

Here is one version with a simple use of Reduce :

x  <- rnorm(100)
ss <- seq(95, 5, -5)

draws <- Reduce(sample, ss, x, accumulate=TRUE)
means <- sapply(draws, mean)

Or in a single line:

means <- sapply(Reduce(sample, seq(95, 5, -5), rnorm(100), accumulate=TRUE), mean)

You may use mapply .

set.seed(42)
x <- rnorm(100); s <- c(19:1*5,1)

(res <- mapply(function(x, ...) mean(sample(x, ...)), list(x), s))
# [1]  0.07869899  0.04229915  0.03902743  0.01012935  0.05068990 -0.06091937
# [7]  0.01686019  0.15820150  0.03205169 -0.08031480 -0.25243403 -0.14227557
# [13] -0.08546622  0.09478834 -0.13369267  0.09708245  0.20528372  0.17391816
# [19] -0.54889423 -0.36105730

Note, that:

length(res) == length(s)
# [1] TRUE

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