r - 分组的新日期列
问题描述
我的数据框中有日期,我想创建一个新变量,在其中使用日期将它们分组为时间段。时间段将是
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
谢谢
解决方案
使用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
有factor
s。如果您希望它们作为 strings/ character
,那么
as.character(cut(dat$date_of_delivery, cutoffs, labels = names(cutoffs)[-length(cutoffs)]))
# [1] "1980-1989" "1990-1999" "2000-2012" "1990-1999"
推荐阅读
- python - 动态搜索:Pandas 数据框查询
- c# - c# 文化信息的日期格式问题
- c - 如何将数据从结构或联合复制到没有空字符的缓冲区数组?
- python - 在python中完成连接后,非阻塞套接字是否总是可写的?
- java - 我想缩短这个方法,你能帮我吗?
- octobercms - 将 Viewbag 变量从主题设置传递给组件
- kotlin - 不确定在房间的哪里自动生成主键
- c# - 当有文件存储在 Azure Blob 存储中时触发 API 终结点
- macos - 知道 NSPopoverTouchBarItem 何时会显示其折叠视图
- plugins - 如何让插件执行另一个插件的命令?