【问题标题】:Generate date range from two date columns in R [duplicate]从R中的两个日期列生成日期范围[重复]
【发布时间】:2020-11-03 10:54:38
【问题描述】:

我正在尝试将日期范围分解为 R 中的各个日期,

源表如下:

Id   start_date   end_date    field1
1    01/03/2019   07/03/2019  text1
2    10/04/2019   15/04/2019  text2

我想得到这个输出:

Id date        field1
1  01/03/2019  text1
1  02/03/2019  text1
1  03/03/2019  text1
1  04/03/2019  text1
1  05/03/2019  text1
1  06/03/2019  text1
1  07/04/2019  text1
2  10/04/2019  text2
2  11/04/2019  text2
2  12/04/2019  text2
2  13/04/2019  text2
2  14/04/2019  text2
2  15/04/2019  text2

【问题讨论】:

    标签: r date date-range


    【解决方案1】:

    这行得通吗:

    library(dplyr)
    library(purrr)
    df %>% group_by(Id, field1) %>% mutate(date = map2(lubridate::dmy(start_date), lubridate::dmy(end_date), `:`)) %>% unnest(date) %>% 
       mutate(date = as.Date(date, origin = '1970-01-01')) %>% select(-c(start_date, end_date))
    # A tibble: 13 x 3
    # Groups:   Id, field1 [2]
          Id field1 date      
       <dbl> <chr>  <date>    
     1     1 text1  2019-03-01
     2     1 text1  2019-03-02
     3     1 text1  2019-03-03
     4     1 text1  2019-03-04
     5     1 text1  2019-03-05
     6     1 text1  2019-03-06
     7     1 text1  2019-03-07
     8     2 text2  2019-04-10
     9     2 text2  2019-04-11
    10     2 text2  2019-04-12
    11     2 text2  2019-04-13
    12     2 text2  2019-04-14
    13     2 text2  2019-04-15
    > 
    

    【讨论】:

    • 抛出错误:unnest(date) 中的错误:x 必须是列表向量
    • @RishabhGurjar,你是列因素吗?
    猜你喜欢
    • 2019-08-25
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2023-03-30
    相关资源
    最近更新 更多