[R] Use of Apply to Change Values in Dataframe

Brian.J.GREGOR@odot.state.or.us Brian.J.GREGOR at odot.state.or.us
Wed Sep 18 21:30:06 CEST 2002


I have a question about how apply() works for changing data values.  I am
using it to change NA values to zero, but the question applies to other
value changing operations as well.  If I have a dataframe "Dat" with columns
"a", "b" and "c" and there are some NA values in every column:

If I do:
Dat$a[is.na(Dat$a)] <- 0
then all the NA values are changed to 0 in the vector.

But if I do:
Dat2 <- apply(Dat, 2, function(x) x[is.na(x)] <- 0)
then I get a vector of three zeros (one for each column), not the dataframe
with NAs replaced by zeros.

However, if I define a function:
change.na <- function(x){
x[is.na(x)] <- 0
x
}
and then do:
Dat2 <- apply(Dat, 2, change.na)
I get the result I want.

Why is this?

Brian Gregor, P.E.
Transportation Planning Analysis Unit
Oregon Department of Transportation
Brian.J.GREGOR at odot.state.or.us
(503) 986-4120
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list