Perform action on only some columns using dplyr

Viewed 51

I am wanting to convert strings in character variables to NA's. I can do this with:

d3 <- d3 %>%
  select_if(is.character) %>%
  na_if(., "Missing") %>%
  na_if(., "not done")  

But it obviously only keeps the character variables in the dataset. If I try it without the select_if, I get an error:

> d3 <- d3 %>%
+   na_if(., "Missing") %>%
+   na_if(., "not done")  
Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

Not sure why I'm getting that as I have two date/time variables and they are in POSIXct format:

 $ Date                              : POSIXct, format: "2015-10-26" "2015-12-07" "2016-01-19" "2016-04-11" ...
 $ DOB                               : POSIXct, format: "1967-01-20" "1967-01-20" "1967-01-20" "1967-01-20" ...

Would appreciate some tips. Thanks.

1 Answers

If we want to do this selectively on character columns while leaving the other columns as such, use mutate with across

library(dplyr) # version 1.0.4
d3 <- d3 %>%
   mutate(across(where(is.character), ~ 
                na_if(., "Missing") %>% 
                na_if("not_done")))

In the older version of dplyr, it would be mutate_if

d3 %>%
    mutate_if(is.character, ~ na_if(., "Missing") %>%
                              na_if("not_done"))

In the newer version, select_if can be replaced with

d3 %>%
    select(where(is.character))
Related