[R] Logical function to turn missing values to 0's

Gustavo Carvalho gustavo.bio+R at gmail.com
Wed Jan 14 23:41:50 CET 2009


Hello rafamoral,

Try this:

ifelse(is.na(x),0,x)

On Wed, Jan 14, 2009 at 8:32 PM, rafamoral <rafa_moral2004 at yahoo.com.br> wrote:
>
> I have a dataset which contains some missing values, and I need to replace
> them with zeros. I tried using the following:
>
> x <- matrix(data=rep(c(1,2,3,NA),6), ncol=6, nrow=6)
>
> y <- matrix(data=0, ncol=ncol(x), nrow=nrow(x))
>
> for(i in 1:nrow(x)) {
>
> for(j in 1:ncol(x)) {
>
> y[i,j] <- ifelse(x[i,j]==NA, 0, x[i,j])
>
> }}
>
> But y returns an NA matrix.
> I'd appreciate any help.
> --
> View this message in context: http://www.nabble.com/Logical-function-to-turn-missing-values-to-0%27s-tp21466785p21466785.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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