在 R 中,使用 diff() 后查找每个间隔的开始和结束日期

In R, finding the start and end dates for each interval after using diff()

我正在使用 diff() 查找列中变量的差异。但是,我还想显示发现差异的日期。 例如:

Dates <- c("2017-06-07","2017-06-10","2017-06-15","2017-07-07","2017-07-12","2017-07-18")
Variable<-c(5,6,7,8,9,3)
dd<-diff(Dates)
dv<-diff(Variable)

我想找到一种方法来为每个时间间隔的开始日期和结束日期添加列,因此 "06-07" 作为开始日期,"06-10" 作为结束日期,以求两者之间的差异前 2 个变量。有什么想法吗?

您在寻找日期差异吗?

diff(as.Date(as.character(Dates,format="%Y-%M-%D")))

OP 已请求为每个间隔添加开始日期和结束日期列。

这可以通过使用 head()tail() 函数来完成:

# data provided by OP
Dates <- c("2017-06-07","2017-06-10","2017-06-15","2017-07-07","2017-07-12","2017-07-18")
Variable<-c(5,6,7,8,9,3)

start <- head(Dates, -1)   # take all Dates except the last one
end <- tail(Dates, -1L)    # take all Dates except the first one
dd <- diff(as.Date(Dates))   # coersion to class Date required for date arthmetic
dv <- diff(Variable)

# create data.frame of intervals
intervals <- data.frame(start, end, dd, dv)
intervals
       start        end      dd dv
1 2017-06-07 2017-06-10  3 days  1
2 2017-06-10 2017-06-15  5 days  1
3 2017-06-15 2017-07-07 22 days  1
4 2017-07-07 2017-07-12  5 days  1
5 2017-07-12 2017-07-18  6 days -6

请注意 intervals 有 5 行,而构建它的断点向量 Dates 的长度为 6。