r - R - Data.table 聚合 - 需要哪种类型的连接?
问题描述
再一次,我有一个简单的问题让我发疯。
Data.table 结构如下所示。我有两个彼此相似但结构相同的 data.table。它需要“合并”到第一个表,但还需要在第二个表中保留具有不匹配行/值的行。N_Events
是按 分组的事件的计数器变量Date
。每个表都存储计数器变量。
挑战:两个表不存储相同的日期。
Date_1 N_Events_1
1990-01-01 1
1992-02-01 3
1992-02-01 3
1992-02-01 3
1997-04-01 2
1997-04-01 2
Date_2 N_Events_2
1990-01-01 1
1992-02-01 4
1992-02-01 4
1992-02-01 4
1992-02-01 4
1999-04-01 1
我很想提取每个唯一日期的 N_events以获取下表,然后加入它们。我也很想将中间结果存储在 dt 中。
# Intermediate aggregation results stored in dt_summ_1
Date_1 N_Events_1
1990-01-01 1
1992-02-01 3
1997-04-01 2
# Intermediate aggregation results stored in dt_summ_2
Date_2 N_Events_2
1990-01-01 1
1992-02-01 4
1999-04-01 1
Date N_Events_1 N_Events_2
1990-01-01 1 1
1992-02-01 3 4
1997-04-01 2 NA
1999-04-01 NA 1
# NAs could also be stored as zero as I subsequently convert
# the NAs to zero to allow plotting the time series of N_Events 1 & 2
到目前为止我已经尝试过:
setkey(dt, Date)
dt_1[, N_Events, by = Date] # not giving me unique dates
dt_1[, .(unique(Date), N_Events)] # warning about item 1 (being date) being recycled with remainder
merge(dt_1, dt_2, by.x = "Date_1", by.y = "Date_2, all = TRUE)
# Errors in 185736 rows; more than 37510 = nrow(x)+nrow(i).
# Check for duplicate key values in i each of which join to the
# same group in x over and over again.
我在这里做错了什么?任何指针高度赞赏!
解决方案
如果我没记错的话,我认为你应该寻找full_join()
dplyr 包的功能。您将在日期列上将它们连接在一起。如果一个 df 中缺少日期,它将在相应的事件 1 或 2 列中给出 NA。
推荐阅读
- typescript - 如何为一组输入定义类型,这些输入映射到 TypeScript 中函数的一组输出?
- powershell - Powershell:调用Parent的空构造函数的继承类,即使传递了对象
- java - Java:为什么 else 语句总是在我的 while 循环中运行?
- python - Python Pandas 复合聚合不等于单个资产复合的总和
- python - 如何计算 Sklearn 中点到质心的平均距离的平均值?
- r - 如何使用列名向量作为 dplyr::group_by() 的输入?
- azure - 如何将用户分配的托管标识添加到 Azure 实验室 VM?
- unreal-engine4 - 错误:无法实例化模块“启动”:System.FormatException:输入字符串的格式不正确
- graphql - Shopify GraphQL Checkout 创建突变
- reactjs - react-datetime timeConstraints for timePicker 似乎不起作用