Fill in missing date ranges

人盡茶涼 提交于 2021-01-27 06:41:55

问题


I have the following example data frame:

Date_from <- c("2013-01-01","2013-01-10","2013-01-16","2013-01-19")
Date_to <- c("2013-01-07","2013-01-12","2013-01-18","2013-01-25")
y <- data.frame(Date_from,Date_to)
y$concentration <- c("1.5","2.5","1.5","3.5")
y$Date_from <- as.Date(y$Date_from)
y$Date_to <- as.Date(y$Date_to)
y$concentration <- as.numeric(y$concentration)

These are measurend concentrations of heavy metals for a specific date range. However, the date ranges are not consecutive as there are gaps between 2013-01-07 to 2013-01-10 and 2013-01-12 to 2013-01-16. I need to detect those gaps, insert a row after each gap and fill it with the missing range. The result should look like this:

Date_from    Date_to concentration
2013-01-01 2013-01-07           1.5
2013-01-08 2013-01-09            NA
2013-01-10 2013-01-12           2.5
2013-01-13 2013-01-15            NA
2013-01-16 2013-01-18           1.5
2013-01-19 2013-01-25           3.5

回答1:


Try this:

adding <- data.frame(Date_from = y$Date_to[-nrow(y)]+1,
                     Date_to = y$Date_from[-1]-1, concentration = NA)
adding <- adding[adding$Date_from <= adding$Date_to,]
res <- rbind(y,adding)
res[order(res$Date_from),]

#   Date_from    Date_to concentration
#1 2013-01-01 2013-01-07           1.5
#5 2013-01-08 2013-01-09            NA
#2 2013-01-10 2013-01-12           2.5
#6 2013-01-13 2013-01-15            NA
#3 2013-01-16 2013-01-18           1.5
#4 2013-01-19 2013-01-25           3.5



回答2:


Here's a solution that requires magrittr and dplyr. It finds the gaps, then loops through to fill them.

# Locations to pad data frame
tmp <- which(y$Date_from-lag(y$Date_to) > 1) 
tmp <- tmp + (1:length(tmp)) - 1

for(i in tmp) {
  # Add row
  y %<>% add_row(Date_from = y$Date_to[i-1] + 1, 
                 Date_to = y$Date_from[i] - 1, 
                 .before = i)
}

#    Date_from    Date_to concentration
# 1 2013-01-01 2013-01-07           1.5
# 2 2013-01-08 2013-01-09            NA
# 3 2013-01-10 2013-01-12           2.5
# 4 2013-01-13 2013-01-15            NA
# 5 2013-01-16 2013-01-18           1.5
# 6 2013-01-19 2013-01-25           3.5


来源:https://stackoverflow.com/questions/51174072/fill-in-missing-date-ranges

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!