"which.just.above" <- function(x, reference, strict = T) { # output[k] will be index of smallest value in reference vector # larger than x[k]. If strict=F, replace 'larger than' by # 'larger than or equal to'. # We should allow NA's in x (but we don't). NA's in reference # should not be allowed. if(any(is.na(x)) || any(is.na(reference))) stop("NA's in input") if(strict) i <- c(rep(T, length(reference)), rep(F, length(x)))[order( c(reference, x))] else i <- c(rep(F, length(x)), rep(T, length(reference)))[order(c( x, reference))] i <- cumsum(i)[!i] + 1. i[i > length(reference)] <- NA # i is length of x and has values in range 1:length(reference) or NA # following needed if reference is not sorted i <- order(reference)[i] # following needed if x is not sorted i[order(order(x))] } "which.just.below" <- function(x, reference, strict = T) { # output[k] will be index of largest value in reference vector # less than x[k]. If strict=F, replace 'less than' by # 'less than or equal to'. Neither x nor reference need be # sorted, although they should not have NA's (in theory, NA's # in x are ok, but not in reference). if(any(is.na(x)) || any(is.na(reference))) stop("NA's in input") if(!strict) i <- c(rep(T, length(reference)), rep(F, length(x)))[order( c(reference, x))] else i <- c(rep(F, length(x)), rep(T, length(reference)))[order(c( x, reference))] i <- cumsum(i)[!i] i[i <= 0] <- NA # i is length of x and has values in range 1:length(reference) or NA # following needed if reference is not sorted i <- order(reference)[i] # following needed if x is not sorted i[order(order(x))] } test <- function(x, ref) { data.frame( belowStrict=ref[which.just.below(x,ref,strict=T)], belowNonstrict= ref[which.just.below(x,ref,strict=F)], x=x, aboveNonstrict= ref[which.just.above(x,ref,strict=F)], aboveStrict=ref[which.just.above(x,ref,strict=T)] )[order(x),] } ref <- 11:14 x <- c(10.5, 11, 11.5, 12, 12.5, 13, 13.5, 14, 14.5) print(test(x,ref)) times<-as.POSIXct("2009-05-22") + seq(0, 5 * 24*60*60, len=15) reftimes<-as.POSIXct("2009-05-23") + seq(0, 4 * 24*60*60, by=24*60*60) print(test(times,reftimes))