首页 > 解决方案 > 分组的新日期列

问题描述

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

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

解决方案


使用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。如果您希望它们作为 strings/ character,那么

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

推荐阅读