【问题标题】:Adding date column to dataframe in reference to another date column参考另一个日期列将日期列添加到数据框
【发布时间】:2020-06-12 14:57:38
【问题描述】:

我有一台机器,有时需要维修

service_dates <- c(as.Date("2019/09/04"), as.Date("2019/10/06"), as.Date("2019/11/15"))

机器有时也会运行(不一定是每周一次,但我有一个日期列表)

run_dates <- seq(as.Date("2019/09/03"), by = "week", length.out = 15)

我想确定上次为 run_dates 的每个元素维护机器的时间。我可以像这样手动完成

df <- data.frame(run_dates)

df_target <- df %>% 
  mutate(last_service = case_when(run_dates >= service_dates[3] ~ service_dates[3],
                                  between(run_dates, service_dates[2], service_dates[3]) ~ service_dates[2],
                                  between(run_dates, service_dates[1], service_dates[2]) ~ service_dates[1],
                                  TRUE ~ as.Date("2018/12/31"))) # arbitrary "pre-service" date
    run_dates last_service
1  2019-09-03   2018-12-31
2  2019-09-10   2019-09-04
3  2019-09-17   2019-09-04
4  2019-09-24   2019-09-04
5  2019-10-01   2019-09-04
6  2019-10-08   2019-10-06
7  2019-10-15   2019-10-06
8  2019-10-22   2019-10-06
9  2019-10-29   2019-10-06
10 2019-11-05   2019-10-06
11 2019-11-12   2019-10-06
12 2019-11-19   2019-11-15
13 2019-11-26   2019-11-15
14 2019-12-03   2019-11-15
15 2019-12-10   2019-11-15

如何在不手动调用每个日期范围 (between(Date, service_date[1], service_date[2]) 等的情况下获得 last_service

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    1。 findInterval

    这里有两个解决方案,findInterval 可以完成所有工作。

    第一个是基础 R 解决方案。

    i <- findInterval(run_dates, service_dates)  
    df$last_service <- service_dates[i]
    

    另一个是dplyr 管道。

    library(dplyr)
    
    df_target <- df %>% 
      mutate(i = findInterval(run_dates, service_dates),
             last_service = service_dates[i]) %>%
      select(-i)
    
    df_target
    #    run_dates last_service
    #1  2019-09-04   2019-09-04
    #2  2019-09-11   2019-09-04
    #3  2019-09-18   2019-09-04
    #4  2019-09-25   2019-09-04
    #5  2019-10-02   2019-09-04
    #6  2019-10-09   2019-10-06
    #7  2019-10-16   2019-10-06
    #8  2019-10-23   2019-10-06
    #9  2019-10-30   2019-10-06
    #10 2019-11-06   2019-10-06
    #11 2019-11-13   2019-10-06
    #12 2019-11-20   2019-11-15
    #13 2019-11-27   2019-11-15
    #14 2019-12-04   2019-11-15
    #15 2019-12-11   2019-11-15
    

    2。 cut.Date

    另外两个解决方案,这次是针对 "Date" 类的对象的 cut 方法。

    df$last_service <- as.Date(cut(run_dates, c(service_dates, Inf)))
    

    还有 dplyr 等价物。

    df_target <- df %>% 
      mutate(last_service = as.Date(cut(run_dates, c(service_dates, Inf))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 2022-10-24
      • 1970-01-01
      相关资源
      最近更新 更多