na.rm = TRUE failing to remove NA on unite()

106 Views Asked by At

I have no idea why this is not working.

po <- unite(Need_info[1:5,],"lala",c(5,6,13,14,15,16),na.rm = TRUE,remove = TRUE)

returns

enter image description here

1

There are 1 best solutions below

0
On BEST ANSWER

The issue is probably the columns are factors. Try using :

library(dplyr)
library(tidyr)

Need_info %>%
  mutate_if(is.factor, as.character) %>%
  unite("lala",c(5,6,13,14,15,16),na.rm = TRUE,remove = TRUE)

Using a reproducible example :

df <- data.frame(a = c(letters[1:5], NA), b = c(NA, letters[11:15]))
df %>% unite("lala", c(1, 2), na.rm  =TRUE, remove = TRUE)

#  lala
#1 1_NA
#2  2_1
#3  3_2
#4  4_3
#5  5_4
#6 NA_5

After converting to character :

df %>% 
  mutate_all(as.character) %>%
  unite("lala", c(1, 2), na.rm = TRUE, remove = TRUE)

#  lala
#1    a
#2  b_k
#3  c_l
#4  d_m
#5  e_n
#6    o