填写缺少的日期范围 [英] Fill in missing date ranges

查看:49
本文介绍了填写缺少的日期范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例数据框:

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)

这些是特定日期范围内重金属的测量浓度.但是,日期范围不是连续的,因为2013-01-07至2013-01-10与2013-01-12至2013-01-16之间存在间隔.我需要检测这些间隙,在每个间隙后插入一行,并用缺少的范围填充它.结果应如下所示:

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

推荐答案

尝试一下:

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

这篇关于填写缺少的日期范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆