Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R coalesce two columns but keep both values if not NA

I have a dataframe with two columns of related data. I want to create a third column that combines them, but there are lots of NAs in one or both columns. If both columns have a non-NA value, I want the new third column to paste both values. If either of the first two columns has an NA, I want the third column to contain just the non-NA value. An example with a toy data frame is below:

x <- c("a", NA, "c", "d")
y <- c("l", "m", NA, "o")
df <- data.frame(x, y)

# this is the new column I want to produce from columns x and y above
df$z <- c("al", "m", "c", "do")

I thought coalesce would solve my problem, but I can’t find a way to keep both values if there is a value in both columns. Thanks in advance for any assistance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Another possible solution:

library(dplyr)
df %>% 
  mutate(z = ifelse(is.na(x) | is.na(y), coalesce(x,y), paste0(x,y)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading