Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two columns containing NA values in complementing rows

Suppose I have this dataframe

df <- data.frame(
    x=c(1, NA, NA, 4, 5, NA),
    y=c(NA, 2, 3, NA, NA, 6)

which looks like this

   x  y
1  1 NA
2 NA  2
3 NA  3
4  4 NA
5  5 NA
6 NA  6

How can I merge the two columns into one? Basically the NA values are in complementary rows. It would be nice to also obtain (in the process) a flag column containing 0 if the entry comes from x and 1 if the entry comes from y.

like image 906
Euler_Salter Avatar asked Oct 29 '25 08:10

Euler_Salter


1 Answers

We can try using the coalesce function from the dplyr package:

df$merged <- coalesce(df$x, df$y)
df$flag <- ifelse(is.na(df$y), 0, 1)
df

   x  y merged flag
1  1 NA      1    0
2 NA  2      2    1
3 NA  3      3    1
4  4 NA      4    0
5  5 NA      5    0
6 NA  6      6    1
like image 89
Tim Biegeleisen Avatar answered Oct 31 '25 00:10

Tim Biegeleisen