2

My problem seems similar to this: str_replace (package stringr) cannot replace brackets in r?

But hopefully somebody can help me.

Here's some sample data:

a<- c(1,2,3,4,5)
b<- c("Home", "Rehab", "Home", "Discharged home or self-care (routine discharge) AHR", "Home")
DF<- data.frame(a,b)

There's hundreds of rows, and i'm trying to go through and replace all the "Discharged home or self-care (routine discharge) AHR" with "Home". When I try:

library(tidyverse)  
DF<-DF%>%mutate(b=str_replace(b,"Discharged home or self-care (routine discharge) AHR","Home"))

Nothing happens. If i try similar code to replace all the "Home"'s with something else for instance.... works fine:

DF<-DF%>%mutate(b=str_replace(b,"Home","House"))

So I figure it has something to do with the parentheses, but I'm lost on escaping it. Any ideas?

Joe Crozier
  • 944
  • 8
  • 20

1 Answers1

4

If it is a fixed match, we can use replace from base R along with ==

library(dplyr)
DF%>%
   mutate(b= replace(b,
     b == "Discharged home or self-care (routine discharge) AHR","Home"))

Or in str_replace, specify the fixed because the () are regex metacharacters for capturing groups and by default it is in regex mode .

library(stringr)
DF %>%
  mutate(b=str_replace(b,
     fixed("Discharged home or self-care (routine discharge) AHR"),"Home"))

TO literally evaluate the (, we need to escape (\\() or place it inside square brackets or with fixed wrapper

DF%>%
   mutate(b=str_replace(b,
    "Discharged home or self-care \\(routine discharge\\) AHR","Home"))
akrun
  • 874,273
  • 37
  • 540
  • 662