Reputation: 1247
I have a data frame and I would like to group by the column "State" and "Date" and then summarize the values of the other columns something like this.
df
State Female Male Date
------------------------------
Texas 2 2 01/01/04
Texas 3 1 01/01/04
Texas 5 4 02/01/04
Cali 1 1 05/06/05
Cali 2 1 05/06/05
Cali 3 1 10/06/05
Cali 1 2 10/06/05
NY 10 5 11/06/05
NY 11 6 12/06/05
Outcome expected
df
State Female Male Date
------------------------------
Texas 5 3 01/01/04
Texas 5 4 02/01/04
Cali 3 2 05/06/05
Cali 4 3 10/06/05
NY 10 5 11/06/05
NY 11 6 12/06/05
I tried with group by and summarize but I don´t exactly how con I do the same for 2 columns
My try
df <- df_homicides %>%
group_by(state) %>%
summarise(Female = sum(Female))
``
Thanks for your help!
Upvotes: 4
Views: 9341
Reputation: 887981
We can use summarise
with across
from dplyr
version > = 1.00
library(dplyr)
df %>%
group_by(State, Date) %>%
summarise(across(everything(), sum, na.rm = TRUE), .groups = 'drop')
# A tibble: 6 x 4
# State Date Female Male
# <chr> <chr> <int> <int>
#1 Cali 05/06/2005 3 2
#2 Cali 10/06/2005 4 3
#3 NY 11/06/2005 10 5
#4 NY 12/06/2005 11 6
#5 Texas 01/01/2004 5 3
#6 Texas 02/01/2004 5 4
Or using aggregate
from base R
aggregate(.~ State + Date, df, sum, na.rm = TRUE)
df <- structure(list(State = c("Texas", "Texas", "Texas", "Cali", "Cali",
"Cali", "Cali", "NY", "NY"), Female = c(2L, 3L, 5L, 1L, 2L, 3L,
1L, 10L, 11L), Male = c(2L, 1L, 4L, 1L, 1L, 1L, 2L, 5L, 6L),
Date = c("01/01/2004", "01/01/2004", "02/01/2004", "05/06/2005",
"05/06/2005", "10/06/2005", "10/06/2005", "11/06/2005", "12/06/2005"
)), class = "data.frame", row.names = c(NA, -9L))
Upvotes: 3
Reputation: 39623
Try this. You can use summarise_all()
to aggregate multiple variables with a desired function. Here the code:
library(dplyr)
#Code
df %>% group_by(State,Date) %>%
summarise_all(.funs = sum,na.rm=T)
Output:
# A tibble: 6 x 4
# Groups: State [3]
State Date Female Male
<chr> <chr> <int> <int>
1 Cali 05/06/2005 3 2
2 Cali 10/06/2005 4 3
3 NY 11/06/2005 10 5
4 NY 12/06/2005 11 6
5 Texas 01/01/2004 5 3
6 Texas 02/01/2004 5 4
Some data used:
#Data
df <- structure(list(State = c("Texas", "Texas", "Texas", "Cali", "Cali",
"Cali", "Cali", "NY", "NY"), Female = c(2L, 3L, 5L, 1L, 2L, 3L,
1L, 10L, 11L), Male = c(2L, 1L, 4L, 1L, 1L, 1L, 2L, 5L, 6L),
Date = c("01/01/2004", "01/01/2004", "02/01/2004", "05/06/2005",
"05/06/2005", "10/06/2005", "10/06/2005", "11/06/2005", "12/06/2005"
)), class = "data.frame", row.names = c(NA, -9L))
Upvotes: 1