r - data.table:是否可以合并 .SD 并按组返回一个新的 'sub data table'?

标签 r data.table

我有一个按 idyear 组织的数据表,每年的频率 (freq) 值其中频率至少为 1。每个 ID 的开始和结束年份可能不同。

例子:

> dt <- data.table(id=c('A','A','A','A','B','B','B','B'),year=c(2010,2012,2013,2015,2006,2007,2010,2011),freq=c(2,1,4,3,1,3,5,7))
> dt
   id year freq
1:  A 2010    2
2:  A 2012    1
3:  A 2013    4
4:  A 2015    3
5:  B 2006    1
6:  B 2007    3
7:  B 2010    5
8:  B 2011    7

我想通过 id 完成每个时间序列,即为任何缺失的年份添加 freq=0 的行。所以上面例子的结果应该是这样的:

 id year freq
  A 2010    2
  A 2011    0
  A 2012    1
  A 2013    4
  A 2014    0
  A 2015    3
  B 2006    1
  B 2007    3
  B 2008    0
  B 2009    0
  B 2010    5
  B 2011    7

我从 data.table 开始,我很想知道这是否可行。使用 plyrdplyr 我会为每个子数据帧按 id 使用完整的年列合并操作。是否有与此解决方案等效的 data.table?

最佳答案

我们不能使用基于CJ 的方法,因为缺失的行需要按-id。另一种方法是:

library(data.table)
dt[ dt[, .(year = do.call(seq, as.list(range(year)))), by = .(id)],
    on = .(id, year)
  ][is.na(freq), freq := 0][]
#         id  year  freq
#     <char> <int> <num>
#  1:      A  2010     2
#  2:      A  2011     0
#  3:      A  2012     1
#  4:      A  2013     4
#  5:      A  2014     0
#  6:      A  2015     3
#  7:      B  2006     1
#  8:      B  2007     3
#  9:      B  2008     0
# 10:      B  2009     0
# 11:      B  2010     5
# 12:      B  2011     7

关于r - data.table:是否可以合并 .SD 并按组返回一个新的 'sub data table'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69815130/

相关文章:

R 表函数 : how to coerce order of column names output of table()

R : how to get the rolling mean of a variable over the last few days but only at a given hour?

r - 递归对象和原子对象的定义是什么?

r - 为什么 RStudio View 模式下的逻辑向量不显示长度?

r - 使用命名列表和 `data.table` 在 R `:=` 中设置多列

r - 如何避免在 data.table 中进行向量搜索

r - order data.table along numeric column puttint special Value (residual category) of other column 最后

r - 在 data.table 中向量化 R for 循环

r - 基于第二列增加列

r - 在 R 中一个接一个地显示多个 ggplot2 图(就像 plot.lm 一样)