better way to replace missing values with zero

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

better way to replace missing values with zero

Roger J. Bos
I would like to replace all missing values (NAs) with zero like below--where
ever they may be--but some of the column classes are non-numeric so I get an
error:

>     dim(temp)
[1] 699 313
>     temp[is.na(temp)] <- 0
Error in as.Date.default(value) : do not know how to convert 'value' to
class "Date"
>

So I have to use more conveluted code:

           for (k in c(1:ncol(temp))) {
               if (class(temp[, k])=="numeric") {
                   temp[, k][is.na(temp[, k])] <- 0
               }
           }

This is much more code and requires a for loop.  Can anyone please show me a
better way?

Thanks,

Roger

        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Reply | Threaded
Open this post in threaded view
|

Re: better way to replace missing values with zero

Marco Geraci
I hope this helps:
   
  foo <- data.frame(x=1:3,y=letters[1:3],z=4:6,
w=as.Date(c("02/27/92", "02/27/92", "01/14/92"), "%m/%d/%y"))
foo[2,] <- NA

  foo
   x    y  z          w
1  1    a  4 1992-02-27
2 NA <NA> NA       <NA>
3  3    c  6 1992-01-14
 
 class(foo$w)
[1] "Date"

  mode(foo$w)
[1] "numeric"

a <- sapply(foo, is.numeric)
b <- !sapply(foo, class)=="Date"
 
foo[!complete.cases(foo),a & b] <- 0

  foo
  x    y z          w
1 1    a 4 1992-02-27
2 0 <NA> 0       <NA>
3 3    c 6 1992-01-14

cheers,
  Marco


roger bos <[hidden email]> wrote:
  I would like to replace all missing values (NAs) with zero like below--where
ever they may be--but some of the column classes are non-numeric so I get an
error:

> dim(temp)
[1] 699 313
> temp[is.na(temp)] <- 0
Error in as.Date.default(value) : do not know how to convert 'value' to
class "Date"
>

So I have to use more conveluted code:

for (k in c(1:ncol(temp))) {
if (class(temp[, k])=="numeric") {
temp[, k][is.na(temp[, k])] <- 0
}
}

This is much more code and requires a for loop. Can anyone please show me a
better way?

Thanks,

Roger

[[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
 


               
---------------------------------

 Ring in the New Year with Photo Calendars. Add photos, events, holidays, whatever.
        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html