Home > database >  How do I use a loop to store values into a vector?
How do I use a loop to store values into a vector?

Time:10-03

The vector needs to have 1000 values, and each value comes from taking the mean of a sample from a larger set of data. Here is my code:

xbar10 <- numeric()
for (i in 1:1000) {
  xbar10 <- mean(sample(X, 10))
}

I want to use a loop to store each new value from the mean(sample(X, 10)) into my new vector xbar10 but I'm having trouble getting it to store 100 values, it just returns one.

CodePudding user response:

This can be done using replicate.

#Assuming X is something like this
X <- runif(100)
xbar10 <- replicate(1000, mean(sample(X, 10)))
xbar10

CodePudding user response:

We can use rerun

library(purrr)
X <- runif(100)
xbar10 <- flatten_dbl(rerun(1000, mean(sample(X, 10))))
  • Related