Reputation: 723
I want to find the indices of values in a vector belonging to intervals which are defined by a vector of ending values and 1)"look-back" value interval and 2) previous N values.
Suppose I have
x <- c(1,3,4,5,7,8,9,10,13,14,15,16,17,18) #the vector of interest
v_end <- c(5, 7, 15) #the end values
l<-3 #look-back value interval
N<-3 #number of value to look back
What I want is the second and third columns of the following output.
x i n
[1,] 1 0 1
[2,] 3 1 1
[3,] 4 1 1
[4,] 5 1 1
[5,] 7 1 1
[6,] 8 0 0
[7,] 9 0 0
[8,] 10 0 1
[9,] 13 1 1
[10,] 14 1 1
[11,] 15 1 1
[12,] 16 0 0
[13,] 17 0 0
[14,] 18 0 0
Notice that v_end and l result in three intervals [2,5],[4,7],[12,15]. [2,5] and [4,7] have overlaps, essentially, it is [2,7]. And, v_end and l result in three intervals [1,5], [3,7],[10,15]. Again there are overlapps.
The task is similar to function findInterval{base}, but can not be solved by it.
Upvotes: 1
Views: 142
Reputation: 13122
Having ordered "v_end" and "x" (for the "N" case), the intervals for the "l" case are:
ints = cbind(start = v_end - l, end = v_end)
ints
# start end
#[1,] 2 5
#[2,] 4 7
#[3,] 12 15
Their overlaps could be grouped with:
overlap_groups = cumsum(c(TRUE, ints[-nrow(ints), "end"] < ints[-1, "start"]))
which can be used to reduce the intervals that are overlapping:
group_end = cumsum(rle(overlap_groups)$lengths)
group_start = c(1L, group_end [-length(group_end )] + 1L)
ints2 = cbind(start = ints[group_start, "start"], end = ints[group_end, "end"])
ints2
# start end
#[1,] 2 7
#[2,] 12 15
Then using findInterval
:
istart = findInterval(x, ints2[, "start"])
iend = findInterval(x, ints2[, "end"], left.open = TRUE)
i = as.integer((istart - iend) == 1L)
i
# [1] 0 1 1 1 1 0 0 0 1 1 1 0 0 0
For the case of "N", starting with:
ints = cbind(start = x[match(v_end, x) - N], end = v_end)
ints
# start end
#[1,] 1 5
#[2,] 3 7
#[3,] 10 15
and following the above steps, we get:
#.....
n = as.integer((istart - iend) == 1L)
n
# [1] 1 1 1 1 1 0 0 1 1 1 1 0 0 0
Generally, a convenient tool for such operations is the "IRanges" package which, here, makes the approach straightforward:
library(IRanges)
xrng = IRanges(x, x)
i = as.integer(overlapsAny(xrng, reduce(IRanges(v_end - l, v_end), min.gapwidth = 0)))
i
# [1] 0 1 1 1 1 0 0 0 1 1 1 0 0 0
n = as.integer(overlapsAny(xrng, reduce(IRanges(x[match(v_end, x) - N], v_end), min.gapwidth = 0)))
n
# [1] 1 1 1 1 1 0 0 1 1 1 1 0 0 0
Upvotes: 1