Vectorise找到最近的日期功能 [英] Vectorise find closest date function

查看:118
本文介绍了Vectorise找到最近的日期功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递一个日期向量,并从第二个向量(部分匹配)日期返回最近的日期。

I would like to pass in a vector of dates, and have returned the closest date from a second vector of (partially matching) dates.

以下函数对单个日期进行了所需的操作,但是我无法弄清楚如何将其概括为 searchDate 是一个向量的日期。

The following function does what I require for a single date, however i cannot figure out how to generalise this to the case where searchDate is a vector of dates.

closestDate <- function(searchDate, dateList, roundDown=FALSE){
  if (roundDown) {
    dist2date <- as.Date(dateList) - as.Date(searchDate)
    closest <- which(max(dist2date[dist2date<=0]) == dist2date)
  } else {
    dist2date <- as.Date(dateList) - as.Date(searchDate)
    closest <- which(min(dist2date[dist2date>=0]) == dist2date)
  }
  return(dateList[closest])
}

dateSeq <- seq(as.Date("2011-01-01"), as.Date("2012-12-19"), by='day')
oddDates <- dateSeq[as.logical(1:length(dateSeq) %%2)]

closestDate('2012-12-14', oddDates)
[1] "2012-12-15"

miscDatesLong <- rep(c('2012-12-14', '2012-12-16', '2012-12-18'), 100 )
closestDate(miscDatesLong, oddDates)

closestDate(miscDatesLong, oddDates)
[1] "2012-12-15" "2012-12-17" "2012-12-19"
Warning message:
In unclass(time1) - unclass(time2) :
  longer object length is not a multiple of shorter object length

有人可以帮忙吗?

推荐答案

现在,以示例为基础,仅在一个或多个其他情况下,当时正在检查的特定目标。

Now, with the example, just work on the subset of dates that are less than in one case or greater than in the other case, the particular target being examined at the time.

closestDt <- function(searchDate, dateList, roundDown=FALSE) 
     as.Date( sapply( searchDate , function (x) if( roundDown ){ 
                max( dateList[ dateList <= x ] ) } else {
                min( dateList[ dateList >= x])  } 
           ), "1970-01-01")

这篇关于Vectorise找到最近的日期功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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