[R] inline function in apply

Gabor Grothendieck ggrothendieck at gmail.com
Thu Sep 10 04:30:32 CEST 2009


Try this:

fill.in.1 <- function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x)
apply(data, 2, fill.in.1)

or

fill.in.2 <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
apply(data, 2, fill.in.2)

Note that in both cases a column containing only NAs will be filled
with NaN's.


On Wed, Sep 9, 2009 at 9:41 PM, bwgoudey <bwgoudey at gmail.com> wrote:
>
> I've been trying to filling in the missing variables in a matrix with the
> mean from the column they are in. So the following code does this just fine.
>
> #3X3 matrix where the middle number is missing.
> data=matrix(c(1:4,NA,6:9), 3, 3)
>
> #replace missing values in an vector with the mean of the vector
> fill_in_NA<-function (x)
> {
>        x[is.na(x)]<-sum(x[!is.na(x)])/length(x[!is.na(x)])
>        return(x)
> }
> #replace the missing value with 5 (mean of 4 and 6)
> apply(data, 2, fill_in_NA)
>
>
> I'm curious as to whether or not I can reduce the function with a single
> inline function call (I'm aware that it will be less readable). My initial
> thought was something like
>
> apply(data, 2, function(x)
> (x[is.na(x)]<-sum(x[!is.na(x)])/length(x[!is.na(x)])))
>
> but this returns a single vector. The problem is that the x in my inline
> function doesn't seem to refer to what I thought it did. Could anyway one
> suggest some appropriate code or possible provide me with a better
> understanding of what my current inline function is actually doing?
>
> Thanks in advance
>
>
>
> --
> View this message in context: http://www.nabble.com/inline-function-in-apply-tp25375733p25375733.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list