[R] inline function in apply

bwgoudey bwgoudey at gmail.com
Thu Sep 10 03:41:54 CEST 2009


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.




More information about the R-help mailing list