R - 在数据框中插入缺失日期的行

时间:2014-04-03 10:28:55

标签: r

我的数据框如下:

> head(train)
      S    D       Date
1     1    1 2010-02-05
2     1    1 2010-02-12
3     1    1 2010-02-19

“日期”列每周只有一个日期,对于每个当前日期,我想在上述日期之后的所有缺失日期插入6行。 结果如下:

> head(train)
      S    D       Date
1     1    1 2010-02-05
1     1    1 2010-02-06 <- inserted
1     1    1 2010-02-07 <- inserted
1     1    1 2010-02-08 <- inserted
1     1    1 2010-02-09 <- inserted
1     1    1 2010-02-10 <- inserted
1     1    1 2010-02-11 <- inserted
2     1    1 2010-02-12
etc

4 个答案:

答案 0 :(得分:4)

可能有点矫枉过正,但重点是在“正确”日期的日期加入,然后填写:

library(dplyr)
library(zoo)

train <- data.frame(D = 1:3, S = 4:6, Date = as.Date("2010-02-05") + 7*(1:3))
full.dates <- as.Date(min(train$Date):max(train$Date), origin = "1970-01-01")
db <- data.frame(Date = full.dates)
fixed <- left_join(db, train)

# Fill from top using zoo::na.locf
fixed[ ,c("D", "S")] <- na.locf(fixed[ ,c("D", "S")])

答案 1 :(得分:1)

在包na.locf中使用zoo的另一种方法,您可以在其中创建zoo时间序列,并在xout中使用na.locf参数。 xout指定用于extra- / interpolation的日期范围。

library(zoo)

# either convert raw data to zoo object
z <- read.zoo(text = "S    D       Date
1     1    1 2010-02-05
2     1    1 2010-02-12
3     1    1 2010-02-19", index.column = "Date")

# ...or convert your data frame to zoo
z <- zoo(x = df[ , c("S", "D")], order.by = df$Date)

# create a sequence of dates, from first to last date in original data
tt <- seq(from = min(index(z)), to = max(index(z)), by = "day")

# expand time series to 'tt', and replace each NA with the most recent non-NA prior to it
na.locf(z, xout = tt)

#            S D
# 2010-02-05 1 1
# 2010-02-06 1 1
# 2010-02-07 1 1
# 2010-02-08 1 1
# 2010-02-09 1 1
# 2010-02-10 1 1
# 2010-02-11 1 1
# 2010-02-12 1 1
# 2010-02-13 1 1
# 2010-02-14 1 1
# 2010-02-15 1 1
# 2010-02-16 1 1
# 2010-02-17 1 1
# 2010-02-18 1 1
# 2010-02-19 1 1

答案 2 :(得分:1)

成为一个傻瓜: - ),

library(lubridate)
train
#  D S       date
# 1 1 2 2010-02-05
# 2 1 3 2010-02-12
 ttmp<-train[1,]
 for(j in 1:6) ttmp<-rbind(ttmp,train[1,])
 for(j in 2:7) ttmp[j,3]<-ttmp[j-1,3]+ddays(1)
 ttmp
#  D S       date
# 1 1 2 2010-02-05
# 2 1 2 2010-02-06
# 3 1 2 2010-02-07
# 4 1 2 2010-02-08
# 5 1 2 2010-02-09
# 6 1 2 2010-02-10
# 7 1 2 2010-02-11

newtrain<-rbind(train[1,],ttmp)

然后遍历所有初始行并rbind将它们全部循环。

答案 3 :(得分:1)

您可以通过以下方式获取缺失的行数:

nMiss <- diff(as.Date(train$Date))

然后,您可以重复data.frame的每一行相关的次数:

longTrain <- train[rep(1:nrow(train), times=c(nMiss, 1)),]

您可以按以下方式生成日期偏移:

off <- unlist(lapply(c(nMiss,1)-1, seq, from=0)
longTrain$Date <- as.Date(longTrain$Date)+off

如果要在数据框的末尾添加额外的行,可以将c(nMiss, 1)中的常量1更改为相关的数字。