Home > Software design >  gsub to remove escape string
gsub to remove escape string

Time:06-17

> pname <- "Ratchanon \"TK\" Chantananuwat (Am)"
> gsub(\"TK\", "", pname)
Error: unexpected string constant in "gsub(\"TK\", ""

It is possible to remove the \"TK\" in this persons name?

CodePudding user response:

In base R:

gsub('\\"TK\\"', "", pname)

#> [1] "Ratchanon  Chantananuwat (Am)"

Another possible solution, based on stringr::str_replace:

library(stringr)

str_remove(pname, '\\"TK\\"')

#> [1] "Ratchanon  Chantananuwat (Am)"

CodePudding user response:

I would like to suggest you do it in the following manner. First remove the special chars you have in your string. Then apply gsub() to get rid of the letter/word you may like.

pname <- "Ratchanon \"TK\" Chantananuwat (Am)"
library(stringr)
pname <- str_replace_all(pname, "[[:punct:]]", "") # removes all the special chars
gsub("TK", "", pname)

Hope this might help you!

  • Related