Get rows with distances within certain values from a data frame of ranges in R

Viewed 125

If I have a data frame of ranges:

start end
12    18
22    30
35    40
49    70
81    90
102   110
120   124

How do I get rows with distances within certain lower and upper threshold in R (i.e. the start of the next row - the end of the previous row is within that threshold)?

Let's say, I want to get rows with distances between 5-10, then I would want to get:

start.1 end.1 start.2 end.2
22      30    35      40
35      40    49      70
102     110   120     124

Here, start.2 - end.1 is always between 5-10.

2 Answers
library(dplyr)

df <- data.frame(
  start = c(12,22,35,49,81,102,120),
  end = c(18,30,40,70,90,110,124)
)

df %>%
  mutate(difference = start - lag(end),
         start.1 = lag(start),
         end.1 = lag(end),
         start.2 = start,
         end.2 = end) %>%
  filter(difference >= 5 & difference <= 10) %>%
  select(-c(difference, start, end))

One way using base R

#Get the difference between consecutive start and end values
diffs <- df$start[-1] - df$end[-nrow(df)] 

#Get indices where the condition of difference is satisfied
rows_inds <- which(diffs >= 5 & diffs <= 10)

#cbind the rows present in row_inds and next row 
df1 <- cbind(df[rows_inds, ], df[rows_inds + 1, ])

#Make the columns name unique 
names(df1) <- make.unique(names(df1))

df1
#  start end start.1 end.1
#2    22  30      35    40
#3    35  40      49    70
#6   102 110     120   124
Related