-1
x <- data.frame(Category=factor(c("First", "First", "First", "Second",
                                    "Third", "Third", "Second")), 
                 Frequency=c(10,15,5,2,14,20,3),Category2=factor(c('a','a','b','e','c','a','e')))

I want to sum up Frequency dependent on Category and Category2.

The result should look like this

Category Frequency Category2
    First        25         a
    First         5         b
   Second         5         e
    Third        14         c
    Third        20         a

I have seen this question

How to sum a variable by group

And I tried x <- x %>% group_by(Category,Category2) %>% summarize(sum = sum(Frequency)) which is wrong. And that does not function aggregate(Frequency ~ c(Category,Category2), x, sum)

Thank You

JORIS
  • 59
  • 7

1 Answers1

0

The code you provide give this result:

`summarise()` regrouping output by 'Category' (override with `.groups` argument)
# A tibble: 5 x 3
# Groups:   Category [3]
  Category Category2   sum
  <fct>    <fct>     <dbl>
1 First    a            25
2 First    b             5
3 Second   e             5
4 Third    a            20
5 Third    c            14

(For that warning refer here: How to interpret dplyr message `summarise()` regrouping output by 'x' (override with `.groups` argument)?)

If you need to get exactly what you expect just run:

x %>% 
  group_by(Category,Category2) %>% 
  summarise(Frequency = sum(Frequency)) %>% 
  ungroup() %>% 
  select(Category, Frequency, Category2)

and it will produce this tibble:

`summarise()` regrouping output by 'Category' (override with `.groups` argument)
# A tibble: 5 x 3
  Category Frequency Category2
  <fct>        <dbl> <fct>    
1 First           25 a        
2 First            5 b        
3 Second           5 e        
4 Third           20 a        
5 Third           14 c   
manuzambo
  • 191
  • 7