writing a function to calculate the mean of columns in a dataframe in R

前端 未结 3 1353

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

3条回答
  •  心在旅途
    2021-01-13 23:13

    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)
    

提交回复
热议问题