[R] Replacing NA values when building matrix using tapply

Chris Long galizur at gmail.com
Fri Oct 5 23:55:05 CEST 2007


Hi,

I'm building a matrix m from a data frame d which includes the matrix row,
column and value.

This works well enough:

m <- tapply(d[,"value"],d[,c("row","column")],c)

However, I'd like to replace any missing values with 0, not NA.  The
obvious doesn't work, however:

m <- tapply(d[,"value"],d[,c("row","column")],function(x) {ifelse(is.na(x),0.0,x)})

I can always do this:

m <- tapply(d[,"value"],d[,c("row","column")],c)
m[is.na(m)] <- 0.0

But it's wasteful to process the table again.  Any ideas?
-- 
Christopher D. Long, San Diego Padres, 100 Park Boulevard, San Diego CA

Score: 0, Diff: 1, clong killed by a Harvard Math Team on  1



More information about the R-help mailing list