Search code examples
rnormal-distribution

Return the mean and standard deviation from a single rnorm function call


  1. I am attempting to create a list of lists containing the mean and standard deviation values from a Normal Distribution with Mean of 5, Standard Deviation of 5 and Sample Size of 10 simulated 50,000 times.

    E.g. List = ((5, 5), (5, 5), (5, 5))

  2. I know that I can do the following code to generate a vector containing 50,000 sample means from the above process:

    sample_means_1 <- rep (NA, reps)
    for (i in 1: reps){
        sample_means_1[i] <- mean(rnorm(n_10, 5, 5))
    }
    

    sample_means_1 now contains a vector of 50,000 sample means for sample size of 10

  3. What I don't know is how I can capture the mean and standard deviation from the same run when using rnorm and plug it into a list type structure.

  4. Does it make more sense to try a method that returns values into a dataframe instead?

Thanks,

Ben

Edit

Please note future readers:

  1. Ans in comment generates a list from @user2974951

    lapply(1:10,function(x){temp=rnorm(10);c(mean(temp),sd(temp))}) 
    
  2. Ans Accepted generates a matrix from @James


Solution

  • You can use an anonymous function within replicate to pull out stats from repeated draws from a distribution:

    replicate(5, {function(x) c(mean=mean(x),sd=sd(x))}(rnorm(10,5,5)))
             [,1]     [,2]     [,3]     [,4]     [,5]
    mean 5.372839 4.042219 4.145441 5.148652 5.202886
    sd   3.929017 5.190347 4.802461 5.515714 4.173267