我想将lubridate intervals合并,如果它们重叠,则从时间上最先出现的内部中取最小值,在时间上最后出现的内部中取最大值,并进行汇总以创建跨越整个时间段的新interval。这是一个reprex:
library(lubridate, warn.conflicts = FALSE)
library(dplyr, warn.conflicts = FALSE)
library(tibble)
dat <- tibble(
animal = rep(c("elk", "wolf", "moose"), each = 2),
date_interval = c(
interval(as.Date("2020-04-01"), as.Date("2020-04-05")),
interval(as.Date("2020-04-10"), as.Date("2020-04-15")),
interval(as.Date("2020-03-01"), as.Date("2020-04-01")),
interval(as.Date("2020-02-15"), as.Date("2020-03-15")),
interval(as.Date("2020-10-01"), as.Date("2020-11-01")),
interval(as.Date("2020-09-15"), as.Date("2020-10-15"))
)
)
dat
#> # A tibble: 6 x 2
#> animal date_interval
#> <chr> <Interval>
#> 1 elk 2020-04-01 UTC--2020-04-05 UTC
#> 2 elk 2020-04-10 UTC--2020-04-15 UTC
#> 3 wolf 2020-03-01 UTC--2020-04-01 UTC
#> 4 wolf 2020-02-15 UTC--2020-03-15 UTC
#> 5 moose 2020-10-01 UTC--2020-11-01 UTC
#> 6 moose 2020-09-15 UTC--2020-10-15 UTC
好的,所以在 wolf
和 moose
级别中,我们有重叠的区间。假设这是相同的狼和驼鹿,下面这样会重复计算天数:
dat %>%
group_by(animal) %>%
mutate(time = time_length(date_interval)) %>%
summarise(time_cumu = sum(time))
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 2
#> animal time_cumu
#> <chr> <dbl>
#> 1 elk 777600
#> 2 moose 5270400
#> 3 wolf 5184000
这是我想得到的输出类型,它可以总结重叠的区间:
tibble(
animal = c("elk", "elk", "wolf", "moose"),
date_interval = c(
interval(as.Date("2020-04-01"), as.Date("2020-04-05")),
interval(as.Date("2020-04-10"), as.Date("2020-04-15")),
interval(as.Date("2020-02-15"), as.Date("2020-04-01")),
interval(as.Date("2020-09-15"), as.Date("2020-11-01"))
)
)
#> # A tibble: 4 x 2
#> animal date_interval
#> <chr> <Interval>
#> 1 elk 2020-04-01 UTC--2020-04-05 UTC
#> 2 elk 2020-04-10 UTC--2020-04-15 UTC
#> 3 wolf 2020-02-15 UTC--2020-04-01 UTC
#> 4 moose 2020-09-15 UTC--2020-11-01 UTC
有什么想法?