Change NA to 'no' with uncertain vars

Hi there,

I got two datasets which I joined 1:1. Since not every observation in the left has a observation on the right I have NA in the new on. Now I want to change the NA to "no". Problem is, that I am ahead of my team and don´t know how many variables I will join, but I wan´t to close this task now. Also the variables are factors. I tried this:

dt.full <- left_join(dt.left,dt.right) %>% 
  mutate_at(vars(starts_with("var_")), ~ if_else(is.na(.), "no", .))

and this

dt.full <- left_join(dt.left,dt.right) %>% 
  mutate_at(vars(starts_with("var_")), ~ ifelse(is.na(.), "no", .))

but both doesn´t solve the factor problem.
Can anybody help?
Thanks

if you are using tidyverse, then you will have forcats package which is specialised for using factors conveniently.

left_join(dt.left,dt.right) %>%
  mutate_at(vars(starts_with("var_")), 
              ~ forcats::fct_explicit_na(f = .,
                                          na_level = "no"))

Unfortunately, that did not add NAs to the 'no' category. But in the end I used tidyr with,

left_join(dt.left,dt.right) %>%
  mutate_at(vars(starts_with("var_")), replace_na, "no")

Thank you anyway

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.