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.
>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