means and SD for columns in a dataframe with NA values

前端 未结 3 1607
庸人自扰
庸人自扰 2021-01-20 01:58

I\'m trying to calculate the mean and standard deviation of several columns (except the first column) in a data.frame with NA values.

I\'ve tried

3条回答
  •  暖寄归人
    2021-01-20 01:59

    sapply(df, function(cl) list(means=mean(cl,na.rm=TRUE), sds=sd(cl,na.rm=TRUE)))
          col1     col2     col3     col4     col5    
    means 3        8        12.5     18.25    22.5    
    sds   1.581139 1.581139 1.290994 1.707825 1.290994
    
    as.data.frame( t(sapply(df, function(cl) list(means=mean(cl,na.rm=TRUE), 
                                                  sds=sd(cl,na.rm=TRUE))) ))
         means      sds
    col1     3 1.581139
    col2     8 1.581139
    col3  12.5 1.290994
    col4 18.25 1.707825
    col5  22.5 1.290994
    

提交回复
热议问题