0
votes

Ive created this function to take samples from a random set of numbers that R generates and then compute the mean, standard deviation, and a confidence interval for those numbers. My goal is to try and replicate that in order to simulate a repeated sampling of confidence intervals. However, whenever I run my code with the replicate function, it returns a matrix of values from 1-10000, rather than returning my desired repeated sampling of confidence intervals. Here is my code that I have right now:

SampleCI <- function(n, mu, sigma){
  SRS <- rnorm(n = n, mean = mu, sd = sigma)
  SampleTest <- sample(SRS, size = 15)
  samplestatistics <- c(sum(!is.na(SampleTest)), mean(SampleTest), sd(SampleTest))
  names(samplestatistics) <- c("n", "sample mean", "StdDev")
  
  # 95% CI for mu
  L <- samplestatistics[2] - qt(.975, samplestatistics[1] - 1) * samplestatistics[3] / sqrt(samplestatistics[1])
  U <- samplestatistics[2] + qt(.975, samplestatistics[1] - 1) * samplestatistics[3] / sqrt(samplestatistics[1])
  CI <- c(L,U)
  
  list(samplestatistics = samplestatistics,
       CI = CI
       )
}
PossibleDataset <- SampleCI(100, 25, 3)
NSim = 10^4
testing <- replicate(NSim, PossibleDataset)
testing
1
Your function seems to be doing correct with rnorm and sample - akrun

1 Answers

1
votes

The replicate should be applied while applying the function and not on the output

outlst <- replicate(NSim, SampleCI(100, 25, 3), simplify = FALSE)

In the OP's code, the SampleCI is applied only once and then replicated the output n times