[R] counting Na/not NA by groups by column

Erik Iverson eriki at ccbr.umn.edu
Thu Jun 10 03:16:48 CEST 2010


Hello,

steven mosher wrote:
> # create a matrix with some random NAs in it
>> m<-matrix(NA,nrow=15,ncol=14)
>> m[,3:14]<-52
>> m[13,9]<-NA
>> m[4:7,8]<-NA
>> m[1:2,5]<-NA
>> m[,2]<-rep(1800:1804, by=3)
>> y<-order(m[,2])
>> m<-m[y,]
>> m[,1]<-rep(1:3,by=5)

> 
> # what we want is a result that looks like this
>    1800  3   3   2  3  3   2   3   3   3   3   3   3
>    1801  3   3   2  3  3   2   3   3   3   3   3   3
>    1802  3   3   3  3  3   3   2   3   3   3   3   3
>    1803  3   3   3  3  3   2   3   3   3   3   3   3
>    1804  3   3   3  3  3   2   3   3   3   3   3   3
> 

This should work:

apply(m[, 3:14], 2,
       function(x) tapply(x, m[,2], function(x) sum(!is.na(x))))

It uses tapply inside of apply to break up the groups by m[, 2].



More information about the R-help mailing list