1

I am having 2 columns in a dataframe like so

name1     name2
 <NA>      SAM
 JIM       <NA>
 <NA>      <NA>

I am trying to obtain a merged column like so

name1     name2      name3
 <NA>      SAM        SAM
 JIM       <NA>       JIM
 <NA>      <NA>       <NA>

I want to have the column name3 either of the values of name1 or name2 whichever is not NA.

I tried using

df %>% mutate( name3 = ifelse( is.na(name1), name2, name1) )

I read the posts regarding ifelse() which return the size of the logical vector as input here.

df %>% mutate( name3 = ifelse( is.na(name1), return(name2), return(name1)) )

But I still get 1 as output - am not sure why.

Community
  • 1
  • 1
Dinesh
  • 2,194
  • 3
  • 30
  • 52

1 Answers1

2

We can use coalesce from dplyr (assuming the columns are character class)

library(dplyr)
df1 %>% 
    mutate(name3 = coalesce(name1, name2))
#    name1 name2 name3
#1  <NA>   SAM   SAM
#2   JIM  <NA>   JIM
#3  <NA>  <NA>  <NA>

The reason for getting 1 is because the columns are factor. Change the column class to character and the ifelse should work fine

df1 %>% 
   mutate_all(as.character) %>% 
   mutate(name3 = ifelse(is.na(name1), name2, name1)) 
#  name1 name2 name3
#1  <NA>   SAM   SAM
#2   JIM  <NA>   JIM
#3  <NA>  <NA>  <NA>
akrun
  • 874,273
  • 37
  • 540
  • 662