Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code># initiate a tie-breaking function tie.breaker &lt;- function( x , y , la = look.after ){ # if look.after is TRUE, eliminate all values below x # otherwise, eliminate all values above x if ( la ) y[ y &lt; x ] &lt;- NA else y[ y &gt; x ] &lt;- NA # then among the remaining values, figure out the date the shortest distance away z &lt;- which.min( abs( x - y ) )[1] # use [1] to just take the first result, in case y contains duplicate dates # return z return( z ) } # initiate your main function closestDate &lt;- function( searchDate , dateList , look.after = FALSE ){ # apply a which.min( abs( ) ) command to each of the dates given, # across every date in the larger list dist2date &lt;- sapply( # on every element of searchDate.. as.Date( searchDate ) , # ..run the tie.breaker() function tie.breaker , # and each time, pass in the dateList as.Date( dateList ) , # and also the look.after TRUE/FALSE flag look.after ) # return the matching dates in the same order as passed in dateList[ dist2date ] } # try with two input dates searchDate &lt;- c( '2012-12-14' , '2012-11-18' ) # create a few dates to test against.. someDates &lt;- c( '2012-11-12' , '2012-11-17' , '2012-12-15' , '2012-12-13' , '2012-12-15' , '2012-11-17' , '2012-11-20' ) # return the two dates closests to the inputted dates # the first result gives 12/13, because look.after = FALSE closestDate( searchDate , someDates ) # the first result gives 12/15, because look.after = TRUE closestDate( searchDate , someDates , look.after = TRUE ) # reverse the order to prove it still works someDates &lt;- c( '2012-11-12' , '2012-11-17' , '2012-12-13' , '2012-12-15' , '2012-12-13' , '2012-12-15' , '2012-11-17' ) # the first result gives 12/13, because look.after = FALSE closestDate( searchDate , someDates ) # the first result gives 12/15, because look.after = TRUE closestDate( searchDate , someDates , look.after = TRUE ) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload