Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create vector of all numbers between row values

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading