Populate column in DF based on integer range

Viewed 22

I have a df that contains two columns (Start, End). How can I create a boolean flag that equals 1 when a number is within the start/end range and 0 when not within the range?

Data:

Start <- c(1,6)
End <- c(3,9)

Based on the above ranges, the boolean flag would look like

Integers <- c(1,2,3,4,5,6,7,8,9,10)
Flag <- c(1,1,1,0,0,1,1,1,1,0)
1 Answers

Here is one way to do it that does not assume only 2 ranges:

z <- apply(cbind(Start, End), 1, function(x) x[1] <= Integers & x[2] >= Integers)
Flag <- as.numeric(apply(z, 1, any))
Flag
#  [1] 1 1 1 0 0 1 1 1 1 0
Related