【问题标题】:New column of dates grouped分组的新日期列
【发布时间】:2020-12-07 22:19:22
【问题描述】:

我的数据框中有日期,我想创建一个新变量,在其中使用日期将它们分组为时间段。时间段将是

1980-1989 1990-1999 2000-2012

他们是上课日期

date_of_delivery
1984-02-03
1997-08-01
2007-04-25
1999-04-05

新列的样子

date_of_delivery  dod_group
1984-02-03        1980-1989
1997-08-01        1990-1999
2007-04-25        2000-2012
1999-04-05        1990-1999

谢谢

【问题讨论】:

    标签: r


    【解决方案1】:

    使用cut:

    cutoffs <- setNames(as.Date(c("1980-01-01", "1990-01-01", "2000-01-01", "2013-01-01")), c("1980-1989", "1990-1999", "2000-2012", "Future"))
    cutoffs
    #    1980-1989    1990-1999    2000-2012       Future 
    # "1980-01-01" "1990-01-01" "2000-01-01" "2013-01-01" 
    cut(dat$date_of_delivery, cutoffs, labels = names(cutoffs)[-length(cutoffs)])
    # [1] 1980-1989 1990-1999 2000-2012 1990-1999
    # Levels: 1980-1989 1990-1999 2000-2012
    

    factors。如果你想要它们作为字符串/character,那么

    as.character(cut(dat$date_of_delivery, cutoffs, labels = names(cutoffs)[-length(cutoffs)]))
    # [1] "1980-1989" "1990-1999" "2000-2012" "1990-1999"
    

    【讨论】:

      【解决方案2】:

      您可以尝试使用 base R 中的 cut 的 Date 方法。

      data$dod_group <- cut(as.Date(c("1980-01-01",data$date_of_delivery),
                                    "%Y-%m-%d"),
                            breaks = "10 years")[-1]
      data
      #  date_of_delivery  dod_group
      #1       1984-02-03 1980-01-01
      #2       1997-08-01 1990-01-01
      #3       2007-04-25 2000-01-01
      #4       1999-04-05 1990-01-01
      

      我添加了"1980-01-01" 以使小组在该日期开始,并添加breaks = "10 years" 参数以使休息时间为几十年。最后,我用[-1] 对生成的中断向量进行了子集化,以消除初始日期。

      样本数据:

      data <- structure(list(date_of_delivery = c("1984-02-03", "1997-08-01", 
      "2007-04-25", "1999-04-05")), class = "data.frame", row.names = c(NA, 
      -4L))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-01
        • 2020-10-02
        • 2013-09-07
        • 1970-01-01
        • 2011-11-01
        • 2017-02-15
        • 2017-08-19
        • 1970-01-01
        相关资源
        最近更新 更多