[R] Replacing NA values when building matrix using tapply
Gabor Grothendieck
ggrothendieck at gmail.com
Sat Oct 6 02:56:03 CEST 2007
Try this:
xtabs(value ~ row + column, d)[]
On 10/5/07, Chris Long <galizur at gmail.com> wrote:
> 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
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list