Determining the integers / lines between two given integers / lines

48 views Asked by At

I have a large body of text that I am working with in r and I have identified the line numbers containing key text. I have these stored as two different objects: location1 and location2

I want to now create a list of the lines that fall between location1 and location2.

location1  int [1:393] 4 21 38 57 75 93 110 127 144 166 ...
location2  int [1:393] 6 23 41 59 77 95 112 129 147 168 ...

So I am looking for output that looks like:

5 22 39 40 58 76 111 128 145 146 167 

This is more complicated than just location1 + 1 because there are instances where there are multiple lines between location1 and location2. For example, when location1 is 38 and location2 is 41 I would expect to get 39 and 40 in the output.

How do I do this?

Thanks!

2

There are 2 answers

0
Onyambu On BEST ANSWER
 unlist(Map(seq, location1 + 1, location2 - 1))
 [1]   5  22  39  40  58  76  94 111 128 145 146 167
0
akrun On

We can use Map

unlist(Map(`:`, location1 + 1, location2 - 1))
#[1]   5  22  39  40  58  76  94 111 128 145 146 167

Or a Vectorized approach with rep

v1 <- location2 - location1 -1
rep(location1, v1) + sequence(v1)
#[1]   5  22  39  40  58  76  94 111 128 145 146 167

Or using map2

library(purrr)
map2(location1 + 1, location2 - 1, `:`)

which can also be changed as

tmp <- sweep(df11 , 2,c(1, -1), `+`)

do.call(Map, c(f = `:`, unname(tmp)))

data

location1 <- c(4, 21, 38, 57, 75, 93, 110, 127, 144, 166)

location2 <- c(6, 23, 41, 59, 77, 95, 112, 129, 147, 168)
df1 <- data.frame(location1, location2)