首页 > 解决方案 > 如何按 R 上的日期与两年之间的时间合并?

问题描述

所以我有第一个数据集

公司 导向器 目录日期
AB 亚历山大 2014
AB 贾斯汀 2020

然后我们了解到,在 2014 年至 2019 年期间,AB 的董事是亚历山大。

我的第二个数据集是这样的

公司 结果 日期
AB 好的 2014
AB 好的 2015
AB 坏的 2016 年

每年以此类推。我想通过按公司和日期合并来获得这个输出:

公司 结果 日期 导向器
AB 好的 2014 亚历山大
AB 好的 2015 亚历山大
AB 坏的 2016 年 亚历山大

标签: rdataframedatemergedataset

解决方案


在扩展示例中,展示了如何硬编码其他可能的年份值

df_m <- read.table(text = 'Company  Director    Dir_Date
AB  Alexander   2014
AB  Justin  2020', header = T)

df <- read.table(text = ' Company   Results Date
AB  Good    2014
AB  Good    2015
AB  Bad 2016
AB Something  2021', header = T)

library(tidyverse)
df %>% left_join(df_m %>% group_by(Company) %>% complete(Dir_Date = 2000:2021) %>%
                   fill(Director, .direction = 'down'),
                 by = c('Company' = 'Company', 'Date' = 'Dir_Date'))


  Company   Results Date  Director
1      AB      Good 2014 Alexander
2      AB      Good 2015 Alexander
3      AB       Bad 2016 Alexander
4      AB Something 2021    Justin

或者

df_m <- read.table(text = 'Company  Director    Dir_Date
AB  Alexander   2014
AB  Justin  2020', header = T)

df <- read.table(text = ' Company   Results Date
AB  Good    2012
AB  Good    2015
AB  Bad 2016
AB Something  2021', header = T)

library(tidyverse)
df %>% left_join(df_m %>% group_by(Company) %>% complete(Dir_Date = 2000:2021) %>%
                   fill(Director, .direction = 'down'),
                 by = c('Company' = 'Company', 'Date' = 'Dir_Date'))
#>   Company   Results Date  Director
#> 1      AB      Good 2012      <NA>
#> 2      AB      Good 2015 Alexander
#> 3      AB       Bad 2016 Alexander
#> 4      AB Something 2021    Justin

reprex 包于 2021-05-20 创建 (v2.0.0 )


df_m <- read.table(text = 'Company  Director    Dir_Date
AB  Alexander   2014
AB  Justin  2020', header = T)

df <- read.table(text = ' Company   Results Date
AB  Good    2014
AB  Good    2015
AB  Bad 2016', header = T)

library(tidyverse)
df %>% left_join(df_m %>% group_by(Company) %>% complete(Dir_Date = seq(min(Dir_Date), max(Dir_Date), 1)) %>%
                   fill(Director, .direction = 'down'),
                 by = c('Company' = 'Company', 'Date' = 'Dir_Date'))
#>   Company Results Date  Director
#> 1      AB    Good 2014 Alexander
#> 2      AB    Good 2015 Alexander
#> 3      AB     Bad 2016 Alexander

reprex 包于 2021-05-20 创建 (v2.0.0 )


推荐阅读