【问题标题】:apply Function one raw input ,many raws output应用功能一个原始输入,许多原始输出
【发布时间】:2018-05-03 13:31:25
【问题描述】:

我有一张这样的桌子:

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 格式?

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

谢谢

【问题讨论】:

    标签: r apply lapply sapply tapply


    【解决方案1】:

    我们可以使用data.table 来执行此操作,按行序列分组,创建从“开始日期”到“结束日期”的序列,将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)
    

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

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

    【讨论】:

    • 没有data.table?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 2011-10-31
    • 2012-12-02
    • 2015-07-15
    相关资源
    最近更新 更多