Home > other >  How do I run a for loop so it generates repeated samples of n observations?
How do I run a for loop so it generates repeated samples of n observations?

Time:02-04

I first generated random data from a Gamma distribution using the following code

data <- rgamma(9, shape=32, scale=1/4)

I proceeded to generate a single sample of 9 observations from the population.

sample(data, 9)

I'm trying to run a for loop in R so that I can repeatedly generate samples of 9 observations and save the mean of each sample into a new vector. I want to do this 500,000 times. After the for loop I then want to create a null distribution based on the distribution created from the for loop. I am also wanting to sample with replacement. (I am also very new to R, so any suggestions or help is greatly appreciated).

Here is the code I have tried for the for loop:

v <- 500000
Storage <- numeric(9)

for (i in v) {
  Storage[i] <- mean(i)
}

CodePudding user response:

The easiest way to do this is like this...

means <- replicate(500000, mean(rgamma(9, shape=32, scale=1/4)))

This will generate 9 gamma variates, take the mean, and repeat the process 500,000 times, storing the result in the vector means. Definitely no need for a for loop!

CodePudding user response:

Use replicate to create the vectors, then compute the means with the fast colMeans.

set.seed(2023)
data <- rgamma(9, shape=32, scale=1/4)

v <- 500000L

Storage <- replicate(v, sample(data, 9, TRUE))

mean_Storage <- colMeans(Storage)
hist(mean_Storage, freq = FALSE)

Created on 2023-02-03 with reprex v2.0.2


Or maybe you want to sample from a Gamma distribution.

set.seed(2023)

v <- 500000L

Storage <- replicate(v, rgamma(9, shape=32, scale=1/4))

mean_Storage <- colMeans(Storage)
hist(mean_Storage, freq = FALSE)

Created on 2023-02-03 with reprex v2.0.2

  •  Tags:  
  • r
  • Related