Just wondering whether it is possible to calculate means for multiple columns by just using the mean function
e.g.
mean(iris[,1])
i
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