0

I want to merge columns to create a new column:

      x    y    z
1  A <NA> <NA>
2  <NA> B <NA>
49 <NA> <NA> C
50 <NA> <NA> C

I want the result:

      x    y    z m
1  A <NA> <NA> A
2  <NA> B <NA> B
49 <NA> <NA> C C
50 <NA> <NA> C C

I checked previous answers, they were all based on summing rows using is.na but it cannot apply to this case where the variable is a character.

halo09876
  • 2,725
  • 12
  • 51
  • 71

1 Answers1

2

Using coalesce from the dplyr package:

df$m <- coalesce(df$x, df$y, df$z)

coalesce behaves the same way as the SQL function, except for NA in R taking the place of NULL in SQL. The above code will return the first non NA value from the x, y, and z columns, in that order.

For a pure base R option, we can try using ifelse with is.na:

df$m <- ifelse(!is.na(df$x), df$x,
            ifelse(!is.na(df$y), df$y, df$z))
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360