Home > Mobile >  cannot mutate string with special characters in r
cannot mutate string with special characters in r

Time:04-28

I have the dataframe below:

library(stringr)
library(dbplyr)

df1 <- data.frame(A = c("4 M",   "56 M",  "89 M",  "25 M",  "50 M",  "NA M"), B = letters[1:6])

I want to replace the "NA M term

df2 <- df1 %>% mutate(A = str_replace(A, "NA M", "TBD"))

this works just fine, but if I add the $ sign

df1 <- data.frame(A = c("$4 M",   "$56 M",  "$89 M",  "$25 M",  "$50 M",  "$NA M"), B = letters[1:6])

df2 <- df1 %>% mutate(A = str_replace(A, "$NA M", "TBD"))

Then nothing happens. How can I account for special characters when using str_replace

CodePudding user response:

We need to escape (\\) or wrap with fixed as $ is a metacharacter suggesting end of string in regex mode (by default, the pattern is in regex mode)

library(dplyr)
library(stringr)
df1 %>%
   mutate(A = str_replace(A, fixed("$NA M"), "TBD"))

-output

      A B
1  $4 M a
2 $56 M b
3 $89 M c
4 $25 M d
5 $50 M e
6   TBD f
  • Related