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

From: Erik Iverson <eriki_at_ccbr.umn.edu>
Date: Wed, 09 Jun 2010 20:16:48 -0500

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].



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 10 Jun 2010 - 01:18:11 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 10 Jun 2010 - 02:30:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive