joker21
joker21

Reputation: 339

How to calculate variance in a data table

I am a nebie to R.I have a data table DT as

id     time     day     type
1        1       9        10
2        2       3        10
1        3       6        12
3        8       9        10
6        9       9        10
8        2       6        18
9        3       5        10
9        1       4        12

From this I initially wanted the count group by day time type.SO i did

DT[,.N,by=list(day,time,type)]

which gives the count for each group.

Now I need to calculate the variance for each group. So I tried

DT[,var(.N),by=list(day,time,type)]  

But this gave NA for all fields.Any help is appreciated.

Upvotes: 0

Views: 1149

Answers (1)

Todd T
Todd T

Reputation: 56

In the example given, there is only a single unique value for many of the combinations, so there is no variance for those rows.

DT <- data.frame (id = c(1,2,1,3,6,8,9,9),
        time = c(1,2,3,8,9,2,3,1),
        day = c(9,3,6,9,9,6,5,4), 
        type = c(10,10, 12, 10,10,18,10,12))

aggregate(DT, list(DT$id), FUN = var)

Upvotes: 1

Related Questions