【问题标题】:Categorical date variable in RR中的分类日期变量
【发布时间】:2015-12-24 19:54:21
【问题描述】:

我有一个非常简单的问题,但我无法弄清楚...我有两个向量,句点和日期,例如:

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

周期是两个中断的向量,设计了 3 个周期:从起点到 2005 年 5 月 1 日,从 2005 年 12 月 1 日到 2009 年 12 月 1 日,从 2009 年 12 月 1 日到结束。我想通过用它们的周期替换日期值来从日期返回一个向量,所以在这个例子中:

[1] 3 1 2

你能告诉我怎么做吗?

非常感谢

【问题讨论】:

  • 两个变量的输出都是NA

标签: r date categories


【解决方案1】:

使用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()。我已将此添加到答案中。
【解决方案2】:

你可以使用一个函数:

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    相关资源
    最近更新 更多