I am learning basics of {dplyr} package in R and working with summarize()
function. When I create groups using group_by()
function, output does not result in summary rows for each group.
The data frame is:
head(titanic_df)
Class Sex Age Survived Freq
1 1st Male Child No 0
2 2nd Male Child No 0
3 3rd Male Child No 35
4 Crew Male Child No 0
5 1st Female Child No 0
Now I group the df by Class
:
head(titanic_df %>% group_by(Class))
# A tibble: 6 x 5
# Groups: Class [4]
Class Sex Age Survived Freq
<fct> <fct> <fct> <fct> <dbl>
1 1st Male Child No 0
2 2nd Male Child No 0
3 3rd Male Child No 35
4 Crew Male Child No 0
5 1st Female Child No 0
This is fine. But when I try to summarize the variable Freq
in this grouped df, output is not grouped by Class
.
titanic_df %>%
group_by(Class) %>%
summarize(num_passg_class = sum(Freq))
num_passg_class
1 2201
The output is a single row of sum of the entire Freq
column, not segregated by Class. Am I missing something?
I am expecting following results:
tapply(titanic_df$Freq, titanic_df$Class, sum)
1st 2nd 3rd Crew
325 285 706 885
PS: This is my first attempt to write formatted R codes at this forum, hope I haven't been terrible at it.
titanic_df
from? $\endgroup$ – william3031 Aug 14 at 2:46