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
Here's an example by slightly modifying your second attempt
mean_fun<-function(x){
mean_c = numeric(0)
for( i in 1:ncol(x)){
s = sum(x[,i], na.rm=TRUE)
l = length(x[,i][is.na(x[,i]) == FALSE])
mean_c[i] = s/l
}
return (mean_c)
}
USAGE
mean_fun(mtcars)
# [1] 20.090625 6.187500 230.721875 146.687500 3.596563 3.217250 17.848750 0.437500 0.406250
#[10] 3.687500 2.812500