Search code examples
rsumaggregate-functions

how to aggregate and sum at the same time in df?


I have a selection of my data frame that looks like this:

Año                             Bien.jurídico.afectado         totalincidencia
1   2015                   La vida y la Integridad corporal              88
2   2015                   La vida y la Integridad corporal              18
3   2016                   Afectaciones         Patrimonio               36
4   2017                   La vida y la Integridad corporal               0
5   2017                   Otros delitos                                  0

What I what is to aggregate the column "Bien.jurídico.afectado" by each category and at the same time sum the column "totalincidencia" to get something like this:

2015     La vida y la integridad corpotal 106 

I have tried different methods without success tho, because either it affects the date when I aggregate or it doesn´t sum the last column.

Any tip will be highly appreciated


Solution

  • Have you tried dplyr?

    library(dplyr)
    
    your_dataframe %>%
       group_by(Año, Bien.jurídico.afectado) %>%
       summarise(total = sum(totalincidencia))