This is my dataframe
year   state    sex   age   population  deaths
-----------------------------------------------
1970   Cal      Male    12     134         45
1970   Cal      Female  12     100         20
1980   Pen      Male    13     200         10
1980   Pen      Female  13     150         50
What I want to do is add the number of deaths and population for each year, and state based on the column sex. And create a new row called Total, with the sum of these values.
I would like to have this:
For each year, example (1970,1980,1990...2050) I have a column called age from 0 to 100. With the number of deaths and population for Male and Female. I want to add the number of population and death for each year,state and age. (keeping the value of age)
I mean I want a third row with the add of Femlaes and Males (Total) and keep the age and year.
    year   state    sex   age   population     deaths
-----------------------------------------------
1970       Cal      Male       12     134         45
1970       Cal      Female     12     100         20
1970       Cal      Total      12     234         65
1980       Pen      Male       13     200         10
1980       Pen      Female     13     150         50
1980       Pen      Total      13     350         60
I tried with this line
df_1 <- setDT(df)[,rbind(.SD,c(.(sex = "Total"),colSums(.SD[,-1]))),state,.SDcols = c("sex",    "population", "deaths", "year", "age")]
But is not giving me the right result. How can I do this?
 
     
    