1

I am trying to merge 2 columns within the same dataset in order to condense the number of columns.

The dataset currently looks like this:

I am trying to merge 2 columns within the same dataset in order to condense the number of columns.

The dataset currently looks like this:

Year Var1 Var2 
2014 123   123 
2014 NA    155 
2015 541   NA 
2015 432   432 
2016 NA    124

I wish the dataset to look like

    Year Var1.2 
    2014 123    
    2014 155
    2015 541   
    2015 432   
    2016 124 

I tried this code:

df$Var1.2 <- paste(df$Var1,df$Var2)

But I can this:

    Year Var1.2 
    2014 123 123 
    2014 NA 155 
    2015 541 NA 
    2015 432 432 
    2016 NA 124

Somewhere had a suggestion?

Curious G.
  • 838
  • 8
  • 23

1 Answers1

4

You can use coalesce

library(dplyr)

df %>% 
  mutate(Var1.2 = coalesce(Var1, Var2)) 

#>   Year Var1 Var2 Var1.2
#> 1 2014  123  123    123
#> 2 2014   NA  155    155
#> 3 2015  541   NA    541
#> 4 2015  432  432    432
#> 5 2016   NA  124    124

Created on 2019-04-11 by the reprex package (v0.2.1.9000)

Tung
  • 26,371
  • 7
  • 91
  • 115
  • Related https://stackoverflow.com/q/14268814/786542 – Tung Apr 11 '19 at 23:33
  • Sorry, I observed a mistake in my final dataset. I obtained the following result: `#> Year Var1 Var2 Var1.2 #> 1 2014 123 123 123 #> 2 2014 NA 155 NA #> 3 2015 541 NA 541 #> 4 2015 432 432 432 #> 5 2016 NA 124 NA` this command replace only the values of right column. – Curious G. Apr 16 '19 at 17:04
  • This message appears: `Warning message: In `[<-.factor`(`*tmp*`, i, value = c(NA, NA, 64L, NA, NA, NA, NA, : invalid factor level, NA generated` – Curious G. Apr 16 '19 at 17:13
  • 1
    The problem was resolved. I solved this problem using this: `df$Var1=as.character.default(df$Var1)` and `df$Var2=as.character.default(df$Var2)`. – Curious G. Apr 16 '19 at 17:46