unite
has got na.rm
parameter which will remove NA
values but for that column needs to be of character type.
library(dplyr)
library(tidyr)
mtcars %>%
mutate_at(vars(NA_1, NA_2), as.character) %>%
unite(Var1, NA_1, NA_2, na.rm = TRUE)
# mpg cyl disp hp drat wt qsec vs am gear carb Var1
#1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 21
#2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 21
#3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 22.8
#4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 21.4
#5 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
#6 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 18.1_18.1
#.....
However, if both the values are NA
then this will return empty values instead of NA
, if we need NA
strictly we can check for empty values and replace
mtcars %>%
mutate_at(vars(NA_1, NA_2), as.character) %>%
unite(Var1, NA_1, NA_2, na.rm = TRUE)
mutate(Var1 = replace(Var1, Var1 == "", NA_character_))
Without any packages we can use paste0
in base R
cols <- c('NA_1','NA_2')
mtcars["V1"] <- apply(mtcars[cols],1,function(x) paste0(na.omit(x), collapse = "-"))