r - 如何按 R 上的日期与两年之间的时间合并?
问题描述
所以我有第一个数据集
公司 | 导向器 | 目录日期 |
---|---|---|
AB | 亚历山大 | 2014 |
AB | 贾斯汀 | 2020 |
然后我们了解到,在 2014 年至 2019 年期间,AB 的董事是亚历山大。
我的第二个数据集是这样的
公司 | 结果 | 日期 |
---|---|---|
AB | 好的 | 2014 |
AB | 好的 | 2015 |
AB | 坏的 | 2016 年 |
每年以此类推。我想通过按公司和日期合并来获得这个输出:
公司 | 结果 | 日期 | 导向器 |
---|---|---|---|
AB | 好的 | 2014 | 亚历山大 |
AB | 好的 | 2015 | 亚历山大 |
AB | 坏的 | 2016 年 | 亚历山大 |
解决方案
在扩展示例中,展示了如何硬编码其他可能的年份值
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 )
推荐阅读
- android - AppAuth或在Android中手动实现OAuth2.0
- sql - QE-DEF-0368 在 IBM Cognos 连接中选择数据源时无法解密用户名和密码
- c++ - 在模板中显示参数类型
- ruby-on-rails - 在另一个页面的 iframe 中打开链接
- powershell - 命令的匹配属性
- javascript - 在反应js中导出表单外的函数
- php - 如何在 Woocommerce 产品中显示运输方式?
- ios - 从我自己的应用程序调用 iOS 照片编辑应用程序?
- firebase - Firebase 实时数据库是否会为写入/上传数据收费?
- batch-file - 批处理:通过一个变量的值访问另一个变量