[R] Use of Apply to Change Values in Dataframe
Roger Peng
rpeng at stat.ucla.edu
Wed Sep 18 23:57:49 CEST 2002
In your second example, the function only returns the subset of 'x' that
was NA. I think what you wanted was:
Dat2 <- apply(Dat, 2, function(x) { x[is.na(x)] <- 0; x })
-roger
_______________________________
UCLA Department of Statistics
rpeng at stat.ucla.edu
http://www.stat.ucla.edu/~rpeng
On Wed, 18 Sep 2002, 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?
>
> 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
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
>
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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