应用函数一个原始输入,多个原始输出

apply Function one raw input ,many raws output

我有一个 table 这样的:

customer   ID    startdate   enddate
11         22   2015-01-01  2015-03-01
11         55   2018-04-03  2018-06-16
22         33   2017-02-01  2017-04-01

这是我想要的输出:

   customer    Id  YearMonth
    11         22   201501
    11         22   201502
    11         22   201503
    11         55   201804
    11         55   201805
    11         55   201806
    22         33   201702
    22         33   201703
    22         33   201704
    22         33   201505

我已经开始写这个函数了:

datseq<-function(t1,t2) {
seq(as.Data(t1), as.Date(t2), by="month")
}

我的问题是:

一个。如何将函数更正为 return me YYYYMM 格式?

b。我如何在数据框上实现此功能,以便每个客户和 ID 都能获得适当的月份列表?输出应该是一个数据框。

谢谢

我们可以使用 data.table 来做到这一点,按行序列分组,创建从 'startdate' 到 'enddate' 的序列,指定 by 为每月和format Date class 到 return 预期格式 ("%Y%m")

library(data.table)
setDT(df1)[, .(customer = customer[1], Id = ID[1], 
 YearMonth = format(seq(startdate, enddate, by = '1 month'), "%Y%m")),
      by = 1:nrow(df1)]

这也可以用tidyverse

来完成
library(tidyverse)
df1 %>% 
  mutate(YearMonth = map2(startdate, enddate, 
       ~ seq(.x, .y, by = "1 month") %>%
              format(., format = "%Y%m"))) %>% 
  select(-startdate, enddate) %>% 
  unnest

如果我们需要一个base R选项,那么可以使用Map

lst <- Map(function(x, y) seq(x, y, by = '1 month'), df1$startdate, df1$enddate)

通过 listlengths 复制数据集的行,并通过连接 list 元素创建列 'YearMonth',然后获得预期的 format

data.frame(df1[rep(1:nrow(df1), lengths(lst)), 1:2], 
           YearMonth = format(do.call(c, lst), "%Y%m"))