如何填补缺失的date?

我有这样的数据:

Date1 Date2 Value2 1/1/1998 1/1/1998 2 1/2/1998 1/2/1998 4 1/3/1998 1/4/1998 6 1/4/1998 1/5/1998 8 1/6/1998 1/6/1998 10 1/7/1998 1/7/1998 12 1/8/1998 1/10/1998 14 1/9/1998 1/10/1998 

我希望Date2与Date1匹配,并在它之前和之后填充缺less的Value2和value2的平均值。

我的最终数据如下所示:

 Date1 Date2 Value 1/1/1998 1/1/1998 2 1/2/1998 1/2/1998 4 1/3/1998 1/3/1998 5 1/4/1998 1/4/1998 6 1/6/1998 1/6/1998 10 1/7/1998 1/7/1998 12 1/8/1998 1/8/1998 13 1/9/1998 1/9/1998 13 1/10/1998 1/10/1998 14 

将你的数据导入到R中(通常你可以从两个文件中读取):

 DF1 <- read.table(text = "Date1 1/1/1998 1/2/1998 1/3/1998 1/4/1998 1/6/1998 1/7/1998 1/8/1998 1/9/1998 1/10/1998", header = TRUE) DF2 <- read.table(text = "Date2 Value2 1/1/1998 2 1/2/1998 4 1/4/1998 6 1/5/1998 8 1/6/1998 10 1/7/1998 12 1/10/1998 14", header = TRUE) 

合并data.frames:

 DF <- merge(DF1, DF2, by.x = "Date1", by.y = "Date2", all.x = TRUE) DF$Date1 <- as.Date(DF$Date1, format = "%m/%d/%Y") #parse dates DF <- DF[order(DF$Date1),] #order the data.frame 

填写均值:

 library(zoo) DF$Value2 <- na.approx(DF$Value2, method = "constant", f = 0.5) # Date1 Value2 # 1 1998-01-01 2 # 3 1998-01-02 4 # 4 1998-01-03 5 # 5 1998-01-04 6 # 6 1998-01-06 10 # 7 1998-01-07 12 # 8 1998-01-08 13 # 9 1998-01-09 13 # 2 1998-01-10 14