Lubridate一个时间间隔向量

4

我正在处理一组lubridate时间间隔,并确定一个日期是否在该集合的任何成员内。 我的时间间隔不重叠,但最好有一个通用答案。)

在开始数据分析之前,我不知道这个时间间隔集合中有多少个时间间隔:


library(lubridate)

#Create 4 dates; 2 pairs

start1 <-ymd("2015-01-01")
stop1 <-ymd("2015-01-08")

start2 <-ymd("2015-02-01")
stop2 <-ymd("2015-02-08")

#Make 2 non-overlapping intervals

interval1 <-start1%--%stop1 

interval2 <-start2%--%stop2 

#two more dates, each within an interval

day1 <-ymd("2015-01-04")

day2 <-ymd("2015-02-04")

#now test the new dates against the intervals.

day1 %within%interval1 #TRUE

day2 %within%interval1 #FALSE

day2 %within%interval2 #TRUE

我可以做到:

day2 %within%c(interval1, interval2) #(FALSE, TRUE)

我相信只要思考一下就可以强制转换成TRUE。

但是我怎么问呢?

#Don't Run:

INTERVALS <-c(interval1, interval2, ... intervalN)

day2 %within% INTERVALS

例如,当Y在工作期间发生X,其中“当Y在工作期间”是时间间隔的矢量。
有什么建议吗?
3个回答

3
您可以对所有内容进行向量化,然后使用lapply来检查您想要检查的每一天是否符合%within%的条件:
library(lubridate)

start <-ymd("2015-01-01", "2015-02-01")
stop <-ymd("2015-01-08", "2015-02-08")

days <-ymd("2015-01-04", "2015-02-04")

lapply(days, `%within%`, start %--% stop)
#> [[1]]
#> [1]  TRUE FALSE
#> 
#> [[2]]
#> [1] FALSE  TRUE

这是一个列出每个days元素是否在每个区间内的列表。要检查每个days元素是否在任何一个区间内,需要为*apply编写一个匿名函数:

sapply(days, function(x){any(x %within% interval(start, stop))})
## [1] TRUE TRUE

1

使用 ivsiv_between() 来确定某个日期是否在 任何 区间之间:

library(ivs)
library(lubridate)

start1 <- ymd("2015-01-01")
stop1 <- ymd("2015-01-08")
start2 <- ymd("2015-02-01")
stop2 <- ymd("2015-02-08")

intervals <- iv_pairs(c(start1, stop1), c(start2, stop2))
intervals
#> <iv<date>[2]>
#> [1] [2015-01-01, 2015-01-08) [2015-02-01, 2015-02-08)

x <- ymd(c("2015-01-04", "2015-02-04"))
x
#> [1] "2015-01-04" "2015-02-04"

# Does `x[i]` fall between any intervals in `intervals`?
iv_between(x, intervals)
#> [1] TRUE TRUE

# If you want to know which intervals it fell between
iv_align(x, intervals, locations = iv_locate_between(x, intervals))
#>      needles                 haystack
#> 1 2015-01-04 [2015-01-01, 2015-01-08)
#> 2 2015-02-04 [2015-02-01, 2015-02-08)

0

你可以使用我的santoku包中的chop()函数:

library(santoku)
chop(c(day1, day2), c(start1, stop1, start2, stop2))
##  [1] [2015-01-01, 2015-01-08) [2015-02-01, 2015-02-08)
## Levels: [2015-01-01, 2015-01-08) [2015-02-01, 2015-02-08)

请注意,这也会捕获stop1和start2之间的任何内容。然后,您可以选择您关心的时间间隔。或者您可以更改标签:
chop(c(day1, day2), c(start1, stop1, start2, stop2), 
       labels = c("Interval1", "Out2", "Interval2"))
## [1] Interval1 Interval2
## Levels: Interval1 Interval2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接