calculate mean for multiple columns in data.frame

后端 未结 3 1093
温柔的废话
温柔的废话 2020-12-16 23:27

Just wondering whether it is possible to calculate means for multiple columns by just using the mean function

e.g.

mean(iris[,1])

i

3条回答
  •  自闭症患者
    2020-12-16 23:57

    With sapply + Filter:

    sapply(Filter(is.numeric, iris), mean)
    Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
        5.843333     3.057333     3.758000     1.199333 
    

    With dplyr:

    library(dplyr)
    iris %>% summarise_each(funs(mean))
       Sepal.Length Sepal.Width Petal.Length Petal.Width Species
    1:     5.843333    3.057333        3.758    1.199333      NA
    

    PS: in dplyr you can now use summarize_if,

    iris %>% summarise_if(is.numeric, mean)
    #>   Sepal.Length Sepal.Width Petal.Length Petal.Width
    #> 1     5.843333    3.057333        3.758    1.199333
    

    With data.table:

    library(data.table)
    iris <- data.table(iris)
    iris[,lapply(.SD, mean)]
       Sepal.Length Sepal.Width Petal.Length Petal.Width Species
    1:     5.843333    3.057333        3.758    1.199333      NA
    

提交回复
热议问题