How to replace value NA in R on specific text match

Viewed 46

sample_df<-

Product Code      Remark
12200234          Done
12200234          Done
12200205          Error
12200256          Error,Pending
12200126          Error,Hold

How I can replace those value which contains text as Error in Remarks column to NA.

OP

Product Code      Remark
12200234          Done
12200234          Done
12200205          NA
12200256          NA
12200126          NA
3 Answers

We could use grepl. It checks for Error string in Remark and replaces with NA

library(dplyr)

sample_df %>% 
  mutate(Remark= case_when(grepl("Error", Remark) ~ "NA",
                           TRUE ~ Remark))

Output:

# A tibble: 5 x 2
  `Product Code` Remark
           <dbl> <chr> 
1       12200234 Done  
2       12200234 Done  
3       12200205 NA    
4       12200256 NA    
5       12200126 NA  

Another option

library(stringr)
library(dplyr)
sample_df %>% 
    mutate(Remark= case_when(str_detect(Remark, "Error") ~ NA_character_,
                       TRUE ~ Remark))
require(gData)

myDf$Remark[startsWith(myDf$Remark, "Error")] <- NA

If you don't want the tidyverse solution given above. As well as grepl, there is also a tidyverse starts_with function...

Related