[R] Use of Apply to Change Values in Dataframe

Jason Turner jasont at indigoindustrial.co.nz
Wed Sep 18 11:53:12 CEST 2002


On Wed, Sep 18, 2002 at 12:30:06PM -0700, Brian.J.GREGOR at odot.state.or.us wrote:
> 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?

Because 0 is the last item evaluated in x[is.na(x)] <- 0.  In 
other words, the following give equivalent results:

function(x) {
	x[is.na(x)] <- 0
}

and

function(x) {
	x[is.na(x)] <- 0
	return(0)
}

Similar to your solution above, this also works:

apply(Dat,2,function(x){x[is.na(x)] <- 0 ; x})

since we've told the function we want the x, not the 0.

One day, I'm gonna buy a computer that does what I 
expect it to, not what I asked it to....   ;)


Jason
-- 
Indigo Industrial Controls Ltd.
64-21-343-545
jasont at indigoindustrial.co.nz
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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