Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace (package stringr) cannot replace brackets in r?

Tags:

r

stringr

I have a string, say

 fruit <- "()goodapple"

I want to remove the brackets in the string. I decide to use stringr package because it usually can handle this kind of issues. I use :

str_replace(fruit,"()","")

But nothing is replaced, and the following is replaced:

[1] "()good"

If I only want to replace the right half bracket, it works:

str_replace(fruit,")","") 
[1] "(good"

However, the left half bracket does not work:

str_replace(fruit,"(","")

and the following error is shown:

Error in sub("(", "", "()good", fixed = FALSE, ignore.case = FALSE, perl = FALSE) : 
 invalid regular expression '(', reason 'Missing ')''

Anyone has ideas why this happens? How can I remove the "()" in the string, then?

like image 463
nan Avatar asked Dec 03 '25 05:12

nan


2 Answers

Escaping the parentheses does it...

str_replace(fruit,"\\(\\)","")
# [1] "goodapple"

You may also want to consider exploring the "stringi" package, which has a similar approach to "stringr" but has more flexible functions. For instance, there is stri_replace_all_fixed, which would be useful here since your search string is a fixed pattern, not a regex pattern:

library(stringi)
stri_replace_all_fixed(fruit, "()", "")
# [1] "goodapple"

Of course, basic gsub handles this just fine too:

gsub("()", "", fruit, fixed=TRUE)
# [1] "goodapple"
like image 174
A5C1D2H2I1M1N2O1R2T1 Avatar answered Dec 04 '25 21:12

A5C1D2H2I1M1N2O1R2T1


The accepted answer works for your exact problem, but not for the more general problem:

my_fruits <- c("()goodapple", "(bad)apple", "(funnyapple")
str_replace(my_fruits,"\\(\\)","")
## "goodapple"  "(bad)apple", "(funnyapple"

This is because the regex exactly matches a "(" followed by a ")".

Assuming you care only about bracket pairs, this is a stronger solution:

str_replace(my_fruits, "\\([^()]{0,}\\)", "")
## "goodapple"   "apple"       "(funnyapple"
like image 20
Charlie Joey Hadley Avatar answered Dec 04 '25 20:12

Charlie Joey Hadley