Home > other >  Replace a text within parentheses in R
Replace a text within parentheses in R

Time:10-08

I need to replace a text when it includes (D) in it.

Here is the sample:

df <- data.frame(id = c(1,2,3),
                 text = c("Student was (D) in X","text1","tex2"))

> df
  id                 text
1  1           Student was (D) in X
2  2                text1
3  3                 tex2

My desired output would be:

> df
      id                 text
    1  1                 Discontinue
    2  2                text1
    3  3                 tex2

I need to replace (D) with Discontinue.

CodePudding user response:

We could use str_replace

library(dplyr)
library(stringr)
df %>% 
   mutate(text = str_replace(text, '.*\\(D\\).*', 'Discontinue'))

-output

  id        text
1  1 Discontinue
2  2       text1
3  3        tex2

CodePudding user response:

Here is one more stringr option combined with ifelse:

library(stringr)
library(dplyr)

df %>% 
  mutate(text = ifelse(str_detect(text, '(D)'), "Discontinue", text))
  id        text
1  1 Discontinue
2  2       text1
3  3        tex2

CodePudding user response:

You could use gsub with fixed = TRUE like this:

df <- data.frame(id = c(1,2,3),
                 text = c("Student was (D) in X","text1","tex2"))

df$text <- gsub("(D)", "Discontinue", df$text, fixed = TRUE)
df
#>   id                         text
#> 1  1 Student was Discontinue in X
#> 2  2                        text1
#> 3  3                         tex2

Created on 2022-10-07 with reprex v2.0.2

  • Related