【问题标题】:Counting dates within interval in R在R中计算区间内的日期
【发布时间】:2018-04-13 17:43:44
【问题描述】:

给定如下一组日期加上每个日期结束的 30 天间隔,我想计算该间隔内的日期数,例如,

library(lubridate)
library(dplyr)
df = data.frame(id = c(1, 2, 3, 4, 5, 6),
               dates = as.Date(c('2017-01-15', '2017-01-17', '2017-02-01', 
                               '2017-02-12', '2017-03-30', '2017-04-01')))

df <- df %>% mutate(interval = interval(dates - 30, dates))

使用

sum(x$dates %within% x$interval[5])

正确返回 1,因为只有一个日期落在第 5 个间隔内,但我想以矢量化方式对所有间隔执行此操作。任何建议表示赞赏。

【问题讨论】:

  • 一种似乎可行的可能性是f &lt;- function(interval, date_vec) { sum(date_vec %within% interval) } df$dates_in_interval &lt;- sapply(df$interval, f, df$dates)
  • colSums(outer(df$dates, df$interval, `%within%`))

标签: r date


【解决方案1】:

使用purrr::map_int,我们可以遍历间隔列并获取每个间隔中的日期数。请注意,这不是“矢量化”的,但我认为可以满足您的需求。

library(lubridate)
library(tidyverse)
df <- data.frame(
  id = c(1, 2, 3, 4, 5, 6),
  dates = as.Date(c(
    "2017-01-15", "2017-01-17", "2017-02-01",
    "2017-02-12", "2017-03-30", "2017-04-01"
  ))
)

df %>%
  mutate(
    interval = interval(dates - 30, dates),
    dates_in_intv = map_int(interval, function(x) sum(.$dates %within% x))
    )
#>   id      dates                       interval dates_in_intv
#> 1  1 2017-01-15 2016-12-16 UTC--2017-01-15 UTC             1
#> 2  2 2017-01-17 2016-12-18 UTC--2017-01-17 UTC             2
#> 3  3 2017-02-01 2017-01-02 UTC--2017-02-01 UTC             3
#> 4  4 2017-02-12 2017-01-13 UTC--2017-02-12 UTC             4
#> 5  5 2017-03-30 2017-02-28 UTC--2017-03-30 UTC             1
#> 6  6 2017-04-01 2017-03-02 UTC--2017-04-01 UTC             2

reprex package (v0.2.0) 于 2018 年 4 月 13 日创建。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    相关资源
    最近更新 更多