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@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.