我有两个数据集:DF1-数据框,其中列出了国家/地区的负责人(leader_id)(country_code)和他们在办公室的时间间隔(office_interval)。DF2-数据框,其中每个观察值都是一个事件,具有国家(country_code)和发生日期(event_date)。
可复制的数据:
library(lubridate)
#Leader DF
leader_id <- c("Adam","Bob","Charlie")
country_code <- c(1,1,2)
office_interval <- c(interval(ymd("1900-01-01"), ymd("1905-01-01")),
interval(ymd("1910-01-01"), ymd("1915-01-01")),
interval(ymd("1920-01-01"), ymd("1925-01-01")))
DF1 <- data.frame(leader_id, country_code, office_interval)
#Event DF
country_code <- c(1,2,2,1)
event_date <- c(as.Date("1901-01-01"),
as.Date("1902-01-01"),
as.Date("1921-01-01"),
as.Date("1901-02-02"))
DF2 <- data.frame(country_code, event_date)
我想创建一个新列DF1 $ total_events,该列将DF1中每个领导者在相同country_code和office_interval内发生的DF2中观察的总数相加。它看起来应该像这样:
leader_id country_code1 office_interval total_events
1 Adam 1 1900-01-01 UTC--1905-01-01 UTC 2
2 Bob 1 1910-01-01 UTC--1915-01-01 UTC 0
3 Charlie 2 1920-01-01 UTC--1925-01-01 UTC 1
我试图从这个类似的问题修改一些解决方案,但是我无法对我的数据进行任何处理。
我们可以做一个left_join
上DF1
并DF2
通过"country_code"
和计数的数量event_date
之内office_interval
。
library(dplyr)
library(lubridate)
DF1 %>%
left_join(DF2, by = "country_code") %>%
group_by(leader_id, country_code, office_interval) %>%
summarise(total_events = sum(event_date %within% office_interval))
# leader_id country_code office_interval total_events
# <fct> <dbl> <Interval> <int>
#1 Adam 1 1900-01-01 UTC--1905-01-01 UTC 2
#2 Bob 1 1900-01-01 UTC--1905-01-01 UTC 0
#3 Charlie 2 1910-01-01 UTC--1915-01-02 UTC 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句