thats beautiful > apply(m[, 3:14], 2, + function(x) tapply(x, m[,2], function(x) sum(!is.na(x)))) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] 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
i was thinking of doing 'by' inside an apply, but this is perfect. thx On Wed, Jun 9, 2010 at 6:16 PM, Erik Iverson <er...@ccbr.umn.edu> wrote: > 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]. > [[alternative HTML version deleted]] ______________________________________________ R-help@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.