Re: [R] better way to replace missing values with zero

From: Marco Geraci <marcodoc75_at_yahoo.com>
Date: Sun 15 Jan 2006 - 06:06:52 EST


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 <roger.bos@gmail.com> 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]]



R-help@stat.math.ethz.ch 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]]



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sun Jan 15 06:21:04 2006

This archive was generated by hypermail 2.1.8 : Sun 15 Jan 2006 - 14:03:56 EST