R中的分类日期变量
Categorical date variable in R
我有一个非常简单的问题,但我无法弄清楚...我有两个向量,句点和日期,例如:
period <- as.Date("2005-05-01","2009-12-01")
date <- ad.Date("2012-01-05","2003-01-24","2006-04-23")
period 是两个中断的向量,正在设计 3 个期间:从 origin 到 2005-05-01,从 2005-12-01 到 2009-12-01,从 2009-12-01 到结束。我想 return 通过用日期值替换日期值来从日期中获取一个向量,所以在这个例子中:
[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
你可以使用函数:
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))
我有一个非常简单的问题,但我无法弄清楚...我有两个向量,句点和日期,例如:
period <- as.Date("2005-05-01","2009-12-01")
date <- ad.Date("2012-01-05","2003-01-24","2006-04-23")
period 是两个中断的向量,正在设计 3 个期间:从 origin 到 2005-05-01,从 2005-12-01 到 2009-12-01,从 2009-12-01 到结束。我想 return 通过用日期值替换日期值来从日期中获取一个向量,所以在这个例子中:
[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
你可以使用函数:
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))