Home > other >  Create vector of all numbers between row values
Create vector of all numbers between row values

Time:08-12

Df <- data.frame(A = c(2, 10, 20, 40),
                 B = c(8,12,25,45))

I want to populate a vector with all values between row 1:column A and row 1:column B, as well as row 2:column A and row2:column B, and so on, for all rows of a dataframe.

So, I want to populate a vector with 2,3,4,5,6,7,8,10,11,12,20,21,22,23,24,25,40,41,42,43,44,45 in this example dataframe, such that I can then see if these values are present elsewhere.

I have tried integer in between options and indexing with for loops, but struggling. Would really appreciate any help. Many thanks.

CodePudding user response:

using tailored function sequence

If we have B >= A for any row, we can simply do:

with(Df, sequence(B - A   1, A))
#[1]  2  3  4  5  6  7  8 10 11 12 20 21 22 23 24 25 40 41 42 43 44 45

If there is B < A in some rows, we need:

## an example
Df[3, ] <- rev(Df[3, ])
#   A  B
#1  2  8
#2 10 12
#3 25 20
#4 40 45

## general solution
with(Df, sequence(abs(B - A)   1, A, sign(B - A)))
#[1]  2  3  4  5  6  7  8 10 11 12 25 24 23 22 21 20 40 41 42 43 44 45

classic loop-based solution

unlist(Map(seq.int, Df$A, Df$B))
  • Related