Home > front end >  Merge two columns, prioritizing values from right-most column
Merge two columns, prioritizing values from right-most column

Time:10-23

Let's say I have a dataset like this:

a      b
dog    <NA>
mouse  <NA>
chad   cat
bird   <NA>

I'd like a merge these columns and resolve conflicts like so

a      
dog    
mouse  
cat   
bird 

So it overrides the values in column a if there's a value present in column b. If there's an NA in column b, ignore.

CodePudding user response:

There is the coalesce function from dplyr

library(tidyverse)

df_example %>%
  mutate(c = coalesce(b,a))

CodePudding user response:

Another solution:

ifelse(is.na(df$b),df$a,df$b)
  • Related