I'm trying to use the dplyr function summarise together with group by to get the sum of my factors. This is my dataset:
brand = c("Mercedes","Mercedes","Mercedes","Mercedes","Mercedes",
"Mercedes","Mercedes","Mercedes","Mercedes","BMW",
"BMW","BMW","BMW","BMW","BMW","BMW","BMW","BMW")
model = c("SL_class", "SL_class", "SL_class", "A_class",
"A_class", "A_class", "E_class", "E_class",
"E_class", "4 Series", "4 Series", "4 Series",
"X1", "X1", "X1", "Z4", "Z4", "Z4")
variable = c(5,6,7,12,13,14,1,2,3,7,8,9,22,24,25,11,12,14)
data = data.frame(brand, model, variable)
data
data$brand <- factor(data$brand)
data$model <- factor(data$model)
But if I try to get the sum of variables
for each level of brand
I do get only a value (see below). Why do I lose the grouping?
data %>%
dplyr::group_by(brand) %>%
summarise(SUM = sum(variable))
SUM
1 195
This is instead the result that I would like to get:
aggregate(data$variable, by = list(data$brand),
FUN =sum)
Group.1 x
1 BMW 132
2 Mercedes 63
Can someone help me to get this working in dplyr?