R中的分类日期变量

3

我有一个非常简单的问题,但是我无法解决它...我有两个向量,周期和日期,如下:

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

period是一个由两个断点组成的向量,用于设计3个时间段:从起始日期到2005-05-01,从2005-12-01到2009-12-01,从2009-12-01到结束日期。我想通过替换日期值为它们所属的时间段来返回一个向量,在这个例子中:

[1] 3 1 2

你能告诉我如何做这个吗?

非常感谢


你的两个变量的输出都是 NA - CuriousBeing
2个回答

5

使用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

不用谢。如果速度很重要,使用findInterval()而不是cut()。我已经将其添加到答案中了。 - Han de Vries

0
你可以使用一个函数:
return_period_position <- function(input_date){

  input_date = as.Date(input_date)
  if(input_date < as.Date("2005-05-01") ){ return(1); }
  else if(input_date > as.Date("2005-05-01") && input_date < as.Date("2009-12-01") ){ return(2); }
  else{ return(3); }

}

dates <- c("2012-01-05","2003-01-24","2006-04-23")

unlist(lapply(dates, return_period_position))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接