FilipeTeixeira
FilipeTeixeira

Reputation: 1160

Merge two columns with Factors and NAs

I have two columns with factors, I wanted to merge. As I have a lot of observations I wonder if there's a quick option with dplyr or tidyr.

Col1    Col2
 A        NA
 B        NA
 NA       C
 A        A
 NA       B
 A        NA
 B        B

I know that this shouldn't be difficult but I'm clearly missing something here. I've tried several options but as I want to keep the factors, all the ones I know didn't work.

Note that when both columns have a result, they will always be the same. But this is part of the data characteristics I have. I expect to have something such as:

Col1    Col2     Col3
 A        NA      A
 B        NA      B
 NA       C       C
 A        A       A
 NA       B       B
 A        NA      A
 B        B       B

Upvotes: 0

Views: 144

Answers (1)

Lucy
Lucy

Reputation: 991

I think this should do it using dplyr:

library('dplyr')
dat %>% 
 mutate(Col3 = if_else(is.na(Col1),Col2, Col1))

Upvotes: 2

Related Questions