1

I have a data.frame with two factor variables. Those two variables contain identical data except for when some values are missing. I want to end up with a data.frame with a third column that contains the complete data.

Example:

df<-data.frame(UID = 1:8,
               A = c("blue", NA, "blue", NA, "green", NA, "green", "green"),
               B = c("blue", "blue", NA, "blue", NA, "green", NA, "green"))

I am looking for the third column to equal;

df$C<-c(rep("blue", 4), rep("green", 4))

I have tried using tidyr::unite to no avail. I know this is probably a bad idea, LOL. I figure there is either a really simple answer or that it is not possible, LOL. Any help is much appreciated.

Dustin
  • 183
  • 7

1 Answers1

1

We can use coalesce

library(dplyr)
df <-  df %>% 
          mutate(C = coalesce(A, B))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    OMG! I knew it was going to be something super simple. I was unfamiliar with this function, so thank you so much for answering! – Dustin Nov 20 '20 at 23:57