Replace a word only when it's a full match case

Hi, I search how to replace my "NA" in my database by real NA. For this i use this code :

commun <- commun %>% mutate(across( .cols = everything() , .fns = ~ gsub("NA",NA, .x)))

but in my data if a name or surname contains NA like "NATACHA" or "PANACOTA", it is also change as a NA, and I don't want this. Do you know how can I subset only when we have the full word, with no letters before of after "NA"

Thank you for your time.

Is this of any help?

library(tidyverse)

df <- tibble(
  x = c("BANANA", "APPLE", "NA", "ORANGE"),
  y = c("NATURE", "INDUSTRY", "ENERGY", "NA")
)

df
#> # A tibble: 4 x 2
#>   x      y       
#>   <chr>  <chr>   
#> 1 BANANA NATURE  
#> 2 APPLE  INDUSTRY
#> 3 NA     ENERGY  
#> 4 ORANGE NA

df %>% mutate(across(.cols = everything(), 
                     .fns = ~ gsub("NA", NA, .x)))
#> # A tibble: 4 x 2
#>   x      y       
#>   <chr>  <chr>   
#> 1 <NA>   <NA>    
#> 2 APPLE  INDUSTRY
#> 3 <NA>   ENERGY  
#> 4 ORANGE <NA>

df %>% mutate(across(.cols = everything(), 
                     .fns = ~ if_else(.x == "NA", NA_character_, .x)))
#> # A tibble: 4 x 2
#>   x      y       
#>   <chr>  <chr>   
#> 1 BANANA NATURE  
#> 2 APPLE  INDUSTRY
#> 3 <NA>   ENERGY  
#> 4 ORANGE <NA>

Created on 2022-04-20 by the reprex package (v2.0.1)

It's perfect thank you!

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.