Replace character with NA (all columns)

library(dplyr)
df <- tibble(
  'name' = c('?', 'B', '?'),
  'location' = c('x','?','z'),
  'age' = c(10, 12, '?')
)
df
#> # A tibble: 3 x 3
#>   name  location age  
#>   <chr> <chr>    <chr>
#> 1 ?     x        10   
#> 2 B     ?        12   
#> 3 ?     z        ?

How do I replace all the ? with NA?

Convert values to NA — na_if • dplyr (tidyverse.org)

1 Like

Thanks! The following code does the job

df %>% 
  mutate(across(where(is.character), ~na_if(., "?")))
#> # A tibble: 3 x 3
#>   name  location age  
#>   <chr> <chr>    <chr>
#> 1 <NA>  x        10   
#> 2 B     <NA>     12   
#> 3 <NA>  z        <NA>

Created on 2021-06-10 by the reprex package (v2.0.0)

This topic was automatically closed 21 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.