欢迎来到 SO,樱桃。将来,请提供可重现的示例,而不是数据框的图片。 dput(your_df_here) 函数可能有用。
这是我的示例数据,与您的不同:
df <- structure(list(STATE = c(1, 1, 1, 2, 2, 2), VETOTAL = c(2, 2, 3, 1, 1, 2), VEFORMS = c(2, 2, 3, 1, 1, 2),
PVHJNVL = c(0, 0, 0, 0, 0, 0), PEDS = c(0, 0, 0, 1, 0, 0), PERSONS = c(3, 2, 4, 1, 1, 2),
PERMVIT = c(3, 2, 4, 1, 1, 2), PERNOTMVI = c(0, 0, 0, 1, 0, 0), COUNTY = c(81, 55, 29, 55, 3, 85),
CITY = c(2340, 1280, 0, 2562, 0, 0), DAY = c(7, 23, 22, 7, 23, 22), MONTH = c(2, 1, 1, 2, 1, 1),
YEAR = c(2019, 2019, 2019, 2019, 2019, 2019), FATALS = c(1, 1, 1, 1, 0, 1), DRUNK_DR = c(1, 0, 0, 0, 1, 0)),
row.names = c(NA, -6L), class = "data.frame")
下面是如何在{tidyverse} 的帮助下创建一个日期观察,按州和日期分组,然后总结一个总和。
library(tidyverse)
df %>%
mutate(date = as.Date(paste(YEAR, MONTH, DAY, sep = "-"))) %>% # create a date
group_by(STATE, date) %>% # Group by State id and date
summarise_at(.vars = vars(VETOTAL:PERNOTMVI, FATALS, DRUNK_DR), sum) ## Summarise a sum of those variables between VETOTAL and PERNOTMVI, plus FATALS and DRUNK_DR
结果:
# A tibble: 6 x 10
# Groups: STATE [2]
STATE date VETOTAL VEFORMS PVHJNVL PEDS PERSONS PERMVIT PERNOTMVI FATALS
<dbl> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 2019-01-22 3 3 0 0 4 4 0 1
2 1 2019-01-23 2 2 0 0 2 2 0 1
3 1 2019-02-07 2 2 0 0 3 3 0 1
4 2 2019-01-22 2 2 0 0 2 2 0 1
5 2 2019-01-23 1 1 0 0 1 1 0 0
6 2 2019-02-07 1 1 0 1 1 1 1 1
填写缺失的日期。
如果您想用 0 填充某个范围内缺失日期的值(即那些没有记录观察的日期),我们可以在 {padr} 的帮助下这样做
library(padr)
df %>%
mutate(date = as.Date(paste(YEAR, MONTH, DAY, sep = "-"))) %>%
group_by(STATE, date) %>%
summarise_at(.vars = vars(VETOTAL:PERNOTMVI, FATALS), sum) %>%
padr::pad(start_val = min(.$date), #This sets the start value as the earliest date present in the "date" variable
end_val = max(.$date)) %>% #This sets the end value as the earliest date present in the "date" variable
fill_by_value(value = 0)
结果:
# A tibble: 34 x 10
# Groups: STATE [2]
STATE date VETOTAL VEFORMS PVHJNVL PEDS PERSONS PERMVIT PERNOTMVI FATALS
<dbl> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 2019-01-22 3 3 0 0 4 4 0 1
2 1 2019-01-23 2 2 0 0 2 2 0 1
3 1 2019-01-24 0 0 0 0 0 0 0 0
4 1 2019-01-25 0 0 0 0 0 0 0 0
5 1 2019-01-26 0 0 0 0 0 0 0 0
6 1 2019-01-27 0 0 0 0 0 0 0 0
7 1 2019-01-28 0 0 0 0 0 0 0 0
8 1 2019-01-29 0 0 0 0 0 0 0 0
9 1 2019-01-30 0 0 0 0 0 0 0 0
10 1 2019-01-31 0 0 0 0 0 0 0 0
# ... with 24 more rows