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

后端 未结 5 1535
南笙
南笙 2020-12-19 14:53

I have data frame looking like this

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

etc.

For each distinct V2 value i would like to calculate v

5条回答
  •  难免孤独
    2020-12-19 15:39

    There are a few ways to do this, I prefer:

    dat <- data.frame(V1 = rnorm(50), V2=rep(1:5,10))
    dat
    
    aggregate (V1~V2, data=dat, var) # The first argument tells it to group V1 based on the values in V2, the last argument simply tells it the function to apply.
    
    > aggregate (V1~V2, data=dat, var)
      V2        V1
    1  1 0.9139360
    2  2 1.6222236
    3  3 1.2429743
    4  4 1.1889356
    5  5 0.7000294
    

    Also look into ddply, daply etc in the plyr package.

提交回复
热议问题