将横截面数据合并到没有 NA 行的面板数据

问题描述

我有 15 个 2005 - 2020 年的数据表,如下所示:

DT_2005 = data.table(
  ID = c("1","2","3","4","5","6"),year = c("2005,"2005","2005")
  score = c("98","89","101","78","97","86")
)

# Data tables for every year...

DT_2020 = data.table(
  ID = c("1","6","7","8"),year = c("2020,"2020","2020")
  score = c("89","79","110","98","74","88")
)

# DT_2020 output
ID,year,score
1,2020,89
2,79
4,110
6,98
7,74
8,88

即有些身份证件几年不见了。

我想将表格组合成这样的“长”格式:

ID,2005,98
1,2006,95
1,2007,97
...
1,2019,90
1,79
2,81
...
2,83
2,79

有没有办法在 data.table 中做到这一点,这样每一行都是一个 ID,年份按升序排列,而 NA' 没有 ID 行不是在某一年?

解决方法

您可以将全局环境中的所有数据帧合并为一个组合数据帧并对结果进行排序。

library(data.table)
dt <- rbindlist(mget(paste0('DT_',c(2005:2020))))
dt <- dt[order(ID)]

等效的 dplyr 和基本 R 替代方案是 -

#dplyr
library(dplyr)
res <- bind_rows(mget(paste0('DT_',c(2005:2020)))) %>% arrange(ID)


#Base R
res <- do.call(rbind,mget(paste0('DT_',c(2005:2020))))
res <- res[order(res$ID),]