通过按日期换行相乘

时间:2019-11-24 22:01:06

标签: r date dataframe reshape

我要转换此表:

  Person  startDate    endDate
 Person1 2018-12-31 2019-03-30
 Person2 2018-12-31 2019-01-30
 Person3 2019-02-01 2019-05-30

df1 <- data.frame(Person = paste0("Person", 1:3),
                  startDate = as.Date(c("31 12 2018", "31 12 2018", "01 02 2019"), format = "%d %m %Y"),
                  endDate = as.Date(c("30 03 2019", "30 01 2019", "30 05 2019"), format = "%d %m %Y"),
                  stringsAsFactors = FALSE)

使用 R

到该表

enter image description here

简而言之:将开始日期和结束日期之间的时间段垂直转换为月表

谢谢!

1 个答案:

答案 0 :(得分:1)

这是一种方法

library(dplyr)
library(purrr)
library(lubridate)
df1 %>%
    transmute(Person, Date = map2(dmy(StartDate), dmy(EndDate), ~
                           seq(.x, .y, by = '1 month') %>%
                                 format('%b %Y'))) %>%
    unnest(Date)
相关问题