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

时间:2018-05-03 13:31:25

标签: r apply lapply sapply tapply

我有一张这样的表:

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")
}

我的问题是:

一个。如何更正函数以返回YYYYMM格式?

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

谢谢

1 个答案:

答案 0 :(得分:2)

我们可以使用data.table执行此操作,按行序列分组,从“开始日期”创建序列。要结束&#39;,将by指定为每月format Date类,以返回预期格式("%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)

lengths的{​​{1}}复制数据集的行,并创建一个列&#39; YearMonth&#39;通过连接list元素然后获得预期的list

format
相关问题