Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: calculate variance for data$V1 for each different value in data$V2

Tags:

r

I have data frame looking like this

V1   V2
..   1
..   2
..   1
..   3

etc.

For each distinct V2 value i would like to calculate variance of data in V1. I have just started my adventure with R, any hints how to do this? for my specific case i guess i can do manually something like

 var1 = var(data[data$V2==1, "V1"])
 var2 = ...

etc because I know all possible V2 values ( there are not many ), however I am curious what would be more generic solutions. Any ideas?

like image 848
mkk Avatar asked Nov 28 '22 10:11

mkk


1 Answers

And the old standby, tapply:

dat <- data.frame(x = runif(50), y = rep(letters[1:5],each = 10))
tapply(dat$x,dat$y,FUN = var)

         a          b          c          d          e 
0.03907351 0.10197081 0.08036828 0.03075195 0.08289562 
like image 128
joran Avatar answered Dec 05 '22 12:12

joran