Find which interval row in a data frame that each element of a vector belongs in

后端 未结 7 825
一整个雨季
一整个雨季 2020-11-29 06:29

I have a vector of numeric elements, and a dataframe with two columns that define the start and end points of intervals. Each row in the dataframe is one interval. I want to

7条回答
  •  野性不改
    2020-11-29 06:40

    Inspired by @thelatemail's cut solution, here is one using findInterval which still requires a lot of typing:

    out <- findInterval(elements, t(intervals[c("start","end")]), left.open = TRUE)
    out[!(out %% 2)] <- NA
    intervals$phase[out %/% 2L + 1L]
    #[1] "a" "a" "a" NA  "b" "b" "c"
    

    Caveat cut and findInterval have left-open intervals. Therefore, solutions using cut and findInterval are not equivalent to Ben's using intrval, David's non-equi join using data.table, and my other solution using foverlaps.

提交回复
热议问题