I have a vector of numeric elements and a data block with two columns that define the start and end points of the intervals. Each row in a data frame is a single interval. I want to know to what interval each element in the vector belongs.
Here are some sample data:
# Find which interval that each element of the vector belongs in library(tidyverse) elements <- c(0.1, 0.2, 0.5, 0.9, 1.1, 1.9, 2.1) intervals <- frame_data(~phase, ~start, ~end, "a", 0, 0.5, "b", 1, 1.9, "c", 2, 2.5)
The same example data for those who mind tidyverse:
elements <- c(0.1, 0.2, 0.5, 0.9, 1.1, 1.9, 2.1) intervals <- structure(list(phase = c("a", "b", "c"), start = c(0, 1, 2), end = c(0.5, 1.9, 2.5)), .Names = c("phase", "start", "end"), row.names = c(NA, -3L), class = "data.frame")
Here is one way to do this:
library(intrval) phases_for_elements <- map(elements, ~.x %[]% data.frame(intervals[, c('start', 'end')])) %>% map(., ~unlist(intervals[.x, 'phase']))
Here's the conclusion:
[[1]] phase "a" [[2]] phase "a" [[3]] phase "a" [[4]] character(0) [[5]] phase "b" [[6]] phase "b" [[7]] phase "c"
But I'm looking for a simpler method with a smaller character set. I saw findInterval in related issues, but I'm not sure how I can use it in this situation.