Search code examples
rrandomsample

Running a rgeom sample and storing the mean and SD of each replication


Trying to run the follow rgeom 500 times and store the mean and sd for each replication.

rgeom(100, prob = .2)

so far I have:

geom_means = rep(NA, 500)
geom_sd = rep(NA, 500)
X_geom500 <- replicate(500, {
  samp <- rgeom(100, prob = .2)
  geom_means = round(mean(samp),2)
})


X_geom500_sd <- replicate(500, {
  samp <- rgeom(100, prob = .2)
  round(sd(samp),2)
})

I can get a vector of 500 means and 500 sd's if I run the code separately but I don't think they are matching. I tried creating a for loop to store the means and SD for each iteration but I don't think it worked right.

for i in range(1:500):
  sample[i] <- rgeom(100, prob = .2)
  geom_means[i] <-  mean(sample[i])
  geom_sd[i] <- sd(sample[i])

Solution

  • You can get both mean and sd from each replication:

    set.seed(123)
    
    n_rep <- 5
    
    samp_geom <- function(n, prob) {
      samp <- rgeom(n, prob)
      return(list(mean = round(mean(samp), 2), sd = round(sd(samp, 2))))
    }
    
    replicate(n_rep, samp_geom(100, .2))
    
         [,1] [,2] [,3] [,4] [,5]
    mean 3.78 3.64 4.09 3.68 3.73
    sd   4    4    5    5    4  
    

    Store the resulting values in separate vectors like this:

    geom_means <- unlist(samps["mean", ])
    geom_means
    # [1] 3.78 3.64 4.09 3.68 3.73
    
    geom_sd <- unlist(samps["sd", ])
    geom_sd
    # [1] 4 4 5 5 4