R中的分类日期变量 [英] Categorical date variable in R

查看:19
本文介绍了R中的分类日期变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题,但我想不出来…我有两个向量,期间和日期如下:

period <- as.Date("2005-05-01","2009-12-01")
date <- ad.Date("2012-01-05","2003-01-24","2006-04-23")

周期是一个由两个中断组成的矢量,设计了3个周期:从起点到2005-05-01,从2005-12-01到2009-12-01,从2009-12-01到结束。我想通过将日期值替换为它们的期间来返回一个来自日期的向量,因此在本例中:

[1] 3 1 2

您能告诉我怎么做吗?

非常感谢

推荐答案

使用cut()findInterval()

period <- as.Date(c("2005-05-01","2009-12-01"))             # note that you need to put the dates in a vector using c()
date <- as.Date(c("2012-01-05","2003-01-24","2006-04-23"))
cut(date, 
    breaks=c(as.Date('1900-01-01'), period, as.Date('3000-01-01')),  # assuming you don't have dates before the year 1900 and after the year 3000
    labels=FALSE)
findInterval(date, 
         c(as.Date('1900-01-01'), period, as.Date('3000-01-01'))))    # faster

这篇关于R中的分类日期变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆