Search code examples
rsamplemean

Seeking mean and SD from multiple sample in R


I want to generate 25 normal samples from an normal distribution. I'm looking to do this in a intelligent manner where I don't have all these samples as separate entities.

This is the code I have so far for that portion

data <- replicate(25, rnorm(100))

So far this is what as it generates 25 samples of 100. When extracting the mean and sd for data, obviously the values are for the entire data set.

So my question is how do I disaggregate this and determine mean and sd for each of the 25 samples?


Solution

  • A nice alternative to apply(x, 2, mean) is colMeans(x), but there's not such alternative for apply(x, 2, sd) :( But you can also get both the mean and the standard deviation in just one shot using apply function, let's do it:

    set.seed(42)
    x <- replicate(25, rnorm(100))
    
    Stats <- t(apply(x, 2, function(x) c(Mean=mean(x), Sd=sd(x))))
    Stats
                  Mean        Sd
     [1,]  0.032514816 1.0413570
     [2,] -0.087483707 0.9041735
     [3,] -0.010368172 1.0170123
     [4,]  0.032936464 0.8761978
     [5,] -0.117830506 1.0199916
     [6,]  0.002363510 1.0633145
     [7,] -0.086747228 0.9755756
     [8,] -0.169291497 0.8830939
     [9,]  0.061457015 1.0377577
    [10,]  0.084205039 1.1804565
    [11,] -0.129164759 1.0080920
    [12,]  0.039991367 0.9814254
    [13,]  0.078980115 0.9719501
    [14,] -0.148572682 0.9125126
    [15,] -0.048566771 0.9562642
    [16,]  0.006789862 1.0347380
    [17,]  0.274102604 1.0212837
    [18,] -0.113169899 0.9988576
    [19,]  0.151418057 0.9830082
    [20,] -0.164987838 0.9348188
    [21,] -0.035644377 1.0214245
    [22,] -0.041569005 1.0159495
    [23,]  0.051384229 1.0944096
    [24,]  0.073521001 0.9084400
    [25,]  0.021893835 0.9438906