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.
CodePudding user response:
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
CodePudding user response:
In base R
, we may also use a row/column indexing
df$col3 <- df[cbind(seq_len(nrow(df)), rep(1:2, length.out = nrow(df)))]
-output
> df
col1 col2 col3
1 A 2 A
2 B 1 1
3 D 2 D
4 F 3 3
5 C 1 C
CodePudding user response:
base
df <- data.frame(col1 = c('A', 'B', 'D', 'F', 'C'), col2 = c(2, 1, 2, 3, 1))
df$col3 <- df$col1
df$col3[c(FALSE, TRUE)] <- df$col2[c(FALSE, TRUE)]
df
#> col1 col2 col3
#> 1 A 2 A
#> 2 B 1 1
#> 3 D 2 D
#> 4 F 3 3
#> 5 C 1 C
Created on 2022-03-06 by the reprex package (v2.0.1)