Alex Alex - 18 days ago 4
R Question

Use summarise_each on grouped data

I am trying to summerise a grouped dataset with

summerise_each
. Somehow it is not possible to drop the grouping variable before summarising (I tried it with
dplyr::select
). The problem is that the grouping variable is not numeric and I want the sum all columns.

library(dplyr)
group <- sample(c("a","b","c"), 100, replace = TRUE,)
values <- matrix(rnorm(1000), ncol = 10)
data <- data.frame(group, values)

data %>% group_by(group) %>% summarise_each(sum)



Error in UseMethod("as.lazy_dots") : no applicable method for
'as.lazy_dots' applied to an object of class "function"


I want this output but for all columns.

data %>% group_by(group) %>% summarise(sum(X1))ยด

group sum(X1)
(fctr) (dbl)
1 a 2.648381
2 b 5.532697
3 c 1.382693


I do not want to use
summarise(sum(X2), sum(X2), ...)

Answer

We need to use the function inside funs

data %>% 
    group_by(group) %>% 
    summarise_each(funs(sum))   

#   group         X1        X2          X3        X4         X5        X6        X7          X8        X9       X10
#  <fctr>      <dbl>     <dbl>       <dbl>     <dbl>      <dbl>     <dbl>     <dbl>       <dbl>     <dbl>     <dbl>
#1      a  -1.700664  3.570311 -0.23851052 7.5914770  0.3646715 -4.547660  8.944908   0.3996188 4.4322264  3.778364
#2      b -12.535340  2.705520 -0.03063312 3.1732708 -5.8638185 -8.070278 -3.548260  -1.7781691 0.7202883 -2.634258
#3      c   9.925093 -7.477544 -0.27394536 0.8187566 -7.7432485 -6.190602 -3.785092 -10.1892073 7.9212578 -2.766949