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

Merge nth elements from two columns while keeping the original row order in R

I am attempting to merge every nth element from col1, replacing values from that same row in col2 in a new column: col3

df <- data.frame(col1 = c('A', 'B', 'D', 'F', 'C'), col2 = c(2, 1, 2, 3, 1))

> df
  col1 col2
1    A    2
2    B    1
3    D    2
4    F    3
5    C    1

If i was to merge every odd element from col1 with every even element from col2, for example, the output should look something like this:

> df
  col1 col2 col3
1    A    2    A
2    B    1    1
3    D    2    D
4    F    3    3
5    C    1    C

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 :

We could do it with an ifelse statement checking if row is even or odd with the modulo operator %%:

library(dplyr)
df %>% 
  mutate(col3 = ifelse((row_number() %% 2) == 0, col2, col1))
  col1 col2 col3
1    A    2    A
2    B    1    1
3    D    2    D
4    F    3    3
5    C    1    C
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