elena
elena

Reputation: 11

R find values from intervals

I have a data frame x:

   begin end
1     1   3
2     5   6
3    11  18

and a vector v <- c(1,2,5,9,10,11,17,20) I'd like to find all values from vector that are elements of any of interval from data frame. So i would like to get a vector c(1,2,5,11,17). How is it possible?

Upvotes: 1

Views: 1287

Answers (2)

d.b
d.b

Reputation: 32558

To get row-wise values, use apply on MARGIN 1 with intersect

apply(df, 1, function(a) intersect(v, a[1]:a[2]))
#[[1]]
#[1] 1 2

#[[2]]
#[1] 5

#[[3]]
#[1] 11 17

OR unlist to get a vector

unlist(apply(df, 1, function(a) intersect(v, a[1]:a[2])))
#OR
intersect(v, unlist(apply(df, 1, function(a) a[1]:a[2]))) #as commented by akrun
#[1]  1  2  5 11 17

Upvotes: 3

akrun
akrun

Reputation: 887881

We can use Map to get the sequence between corresponding, begin/end values in a list, unlist the list and use intersect to get the elements common in both the vectors

intersect(unlist(Map(`:`, x$begin, x$end)), v)
#[1]  1  2  5 11 17

Upvotes: 1

Related Questions