Displaying 1 result from an estimated 1 matches for "fill_in_na".
2009 Sep 10
1
inline function in apply
...;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...