Reputation: 42
I have 30 random samples taken from a data set. I need to calculate sample mean and sample variance for each sample, and arrange them in a table with 3 columns titled "sample", "mean", and "variance".
My dataset is:
lab6data <- c(2,5,4,6,7,8,4,5,9,7,3,4,7,12,4,10,9,7,8,11,8,
6,13,9,6,7,4,5,2,3,10,13,4,12,9,6,7,3,4,2)
I made samples like:
observations <- matrix(lab6data, 30, 5)
and means for every sample separately by:
means <- rowMeans(observations)
Can you please help me to find the variance for every sample separately?
Upvotes: 0
Views: 2259
Reputation: 50678
You can calculate the variance per row using apply
:
apply(observations, 1, var)
Or use rowVars
from the matrixStats
package.
Note that matrixStats::rowVars
will be slightly much faster (see @HenrikB's comment below) than apply(..., 1, var)
, in the same way that rowMeans
is faster than apply(..., 1, mean)
.
Upvotes: 2
Reputation: 887223
We can use pmap
to apply the function on each row of the data.frame
library(purrr)
varS <- pmap_dbl(as.data.frame(observations), ~ var(c(...)))
cbind(observations, varS)
observations <- matrix(lab6data, 10, 4)
Upvotes: 0