0

I would like to merge values from 2 columns into 1. For example, here is sample data:

id   x    y
1   12    NA
1   NA    14  
2   13    NA    
3   15    NA
3   NA    18
4   NA    19

I want

id   x    y     z
1   12    NA    12  
1   NA    14    14  
2   13    NA    13 
3   15    NA    15 
3   NA    18    18
4   NA    19    19

I tried using coalesce to create a new variable.

coalesce <- function(...) {
  apply(cbind(...), 1, function(x) {
    x[which(!is.na(x))[1]]
  })
}

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

However, the variable doesn't reflect the columns joined. Am I using this function incorrectly?



D. Fowler
  • 601
  • 3
  • 7

0 Answers0