如何根据完整索引将 NA 行添加到不完整的数据框中?

How to add NA rows to an incomplete dataframe based on an complete index?

对于给定的不完整数据帧 df 和完整索引 t:

t = seq(as.POSIXct("2016-01-01 00:05:00"), as.POSIXct("2016-01-01 01:00:00"), by = '5 min')
index<-t[c(1,2,4:7,9,12)]
a<-(1:8)
b<-(1:8)
df<-data.frame(index,a,b)

顺便说一句,缺少的行可以通过以下代码添加:

index<-t           #complete index
a<-vector('numeric',12)
a<-NA
b<-vector('numeric',12)
b<-NA
empty_df<-data.frame(index,a,b)         # build an complete NA dataframe
for (i in 1:12) {
 if(!(df$index[i]==empty_df$index[i]))
 df<-rbind(rbind(df[1:i-1,],empty_df[i,]),df[i:length(df$index),])}  # comparison and revison

但是,我的解决方案有两个问题:

  1. 无法处理第一行缺失的情况

  2. 当数据帧很大时,计算将花费数小时。

所以我想知道是否有更简单的方法来处理它?

我们可以使用 mergebase R)或 left_join(来自 dplyr

library(dplyr)
data.frame(index = t) %>%
              left_join(., df)

或从data.table

加入
library(data.table)
setDT(df)[data.table(index=t), on = "index"]