I have to calculate the mean of the columns in a dataframe by writing a function and then applying it. I understand that this is easy to do with mean and
mean
Assuming that all the columns in your data frame are numeric, here is a tweak of your first function, where x is a vector (a column in mydataframe).
mean_fun<-function(x){ mean_c= sum(x,na.rm=TRUE)/length(!is.na(x)) return(mean_c) } apply(mydataframe,2,mean_fun)