Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing/replacing brackets from R string using gsub

Tags:

regex

r

gsub

I want to remove or replace brackets "(" or ")" from my string using gsub. However as shown below it is not working. What could be the reason?

 >  k<-"(abc)"
 >  t<-gsub("()","",k)
 >  t 
[1] "(abc)"
like image 291
itthrill Avatar asked Apr 05 '18 21:04

itthrill


2 Answers

Using the correct regex works:

gsub("[()]", "", "(abc)")

The additional square brackets mean "match any of the characters inside".

like image 125
Martin Schmelzer Avatar answered Oct 06 '22 00:10

Martin Schmelzer


A safe and simple solution that doesn't rely on regex:

k <- gsub("(", "", k, fixed = TRUE) # "Fixed = TRUE" disables regex
k <- gsub(")", "", k, fixed = TRUE)
k
[1] "abc"
like image 30
sindri_baldur Avatar answered Oct 06 '22 00:10

sindri_baldur