Reputation: 25
I would like to know how to find several range in a time sequence. I've got this time sequence :
DATE
1 1996-01-01
2 1996-01-02
3 1996-01-03
4 1998-07-13
5 1998-07-14
6 1998-07-15
7 2000-05-28
I would like to have all time range like that :
[1] "1996-01-01" "1996-01-03"
[2] "1998-07-13" "1998-07-15"
[3] "2000-05-28"
Does someone know how to do? Thank's
Upvotes: 2
Views: 34
Reputation: 886938
An option would be to create a grouping column by taking the difference of adjacent elements and use that create the range
library(dplyr)
library(lubridate)
df1 %>%
mutate(DATE= ymd(DATE)) %>%
group_by(grp = cumsum(c(TRUE, diff(DATE) > 1))) %>%
summarise(min = min(DATE), max = max(DATE))
# A tibble: 3 x 3
# grp min max
# <int> <date> <date>
#1 1 1996-01-01 1996-01-03
#2 2 1998-07-13 1998-07-15
#3 3 2000-05-28 2000-05-28
Or with base R
using split
lapply(with(df1, split(DATE, cumsum(c(TRUE, diff(as.Date(DATE)) > 1)))),
function(x) unique(range(x)))
#$`1`
#[1] "1996-01-01" "1996-01-03"
#$`2`
#[1] "1998-07-13" "1998-07-15"
#$`3`
#[1] "2000-05-28"
df1 <- structure(list(DATE = c("1996-01-01", "1996-01-02", "1996-01-03",
"1998-07-13", "1998-07-14", "1998-07-15", "2000-05-28")),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7"))
Upvotes: 2