我有一个非常简单的问题,但我无法弄明白......我有两个向量,句点和日期如下:
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
你能告诉我怎么做吗?
非常感谢
答案 0 :(得分:4)
使用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
答案 1 :(得分: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))