str_replace (package stringr) cannot replace brackets in r?
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"
Problem escaping the parentheses when using str_replace
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"))
How to replace a caret with str_replace from stringr
An option is to wrap with fixed
and should be fine
library(stringr)
str_replace_all(code, fixed("^"), "")
#[1] "GSPC" "FTSE" "000001.SS" "HSI" "FCHI" "KS11" "TWII" "GDAXI" "STI"
Also, as we are replacing with blank (""
), an option is str_remove
str_remove(code, fixed("^"))
Regarding why the OP's code didn't, inside the square brackets, if we use ^
, it is not reading the literal character, instead the metacharacter in it looks for characters other than and here it is blank ([^]
)
str_replace doesn't replace all occurrences, but gsub does?
It only matches the first occurency, whereas gsub
does it all. Use str_replace_all
instead:
str_replace(string = "aa", pattern = "a", replacement = "b") # only first
str_replace_all(string = "aa", pattern = "a", replacement = "b") # all
Trying to replace a () in a string in R using str_replace
Sub, gsub
\\
identify special characters
If you want to replace ONLY the parenthesis that are in the middle of the string (that is not at the start or at the end):
text <- "tBodyAcc-mean()-X"
sub("#\\(\\)#", "", text)
[1] "tBodyAcc-mean-X"
text <- "tBodyAcc-mean-X()"
sub("#\\(\\)#", "", text)
[1] "tBodyAcc-mean-X()"
If you want to replace ANY parenthesis (including those at the end and at the start of the string)
text <- "tBodyAcc-mean()-X"
sub("\\(\\)", "", text)
EDIT, as pointed out in several comments using gsub
instead of sub
will replace all the "()" in a string, while sub
only replace the first "()"
text <- "t()BodyAcc-mean()-X"
sub("\\(\\)", "", text)
[1] "tBodyAcc-mean()-X"
> gsub("\\(\\)", "", text)
[1] "tBodyAcc-mean-X"
str_replace: replacement depending on wildcard value [A-Z]
It needs to be captured as a group (([A-Z])
) and replace with the backreference (\\1
) of the captured group i.e. regex
interpretation is in the pattern
and not in the replacement
stringr::str_replace("PrinceofWales", "of([A-Z])", " of \\1")
[1] "Prince of Wales"
According to ?str_replace
replacement - A character vector of replacements. Should be either length one, or the same length as string or pattern. References of the form \1, \2, etc will be replaced with the contents of the respective matched group (created by ()).
Or another option is a regex lookaround
stringr::str_replace("PrinceofWales", "of(?=[A-Z])", " of ")
[1] "Prince of Wales"
Removing/replacing brackets from R string using gsub
Using the correct regex works:
gsub("[()]", "", "(abc)")
The additional square brackets mean "match any of the characters inside".
str_replace() escaping question marks in R with a vector from a SPDF, stringr package
library(stringr)
str_replace_all("Is Nuevo Leon in Mexico?",
c("M.xico" = "México", "Nuevo Le.n" = "Nuevo León"))
# [1] "Is Nuevo León in México?"
Related Topics
R: Faceted Bar Chart with Percentages Labels Independent for Each Plot
R Remove Multiple Text Strings in Data Frame
Send a Text String Containing Double Quotes to Function
Ggplot2 One Line Per Each Row Dataframe
Page Refresh Button in R Shiny
Compute All Pairwise Differences Within a Vector in R
How to Rename Element's List Indexed by a Loop in R
Warning: Replacing Previous Import 'Head' When Loading 'Utils' in R
Drawing Non-Intersecting Circles
Using Rvest to Scrape a Website W/ a Login Page
R Shiny - Uioutput Not Rendering Inside Menuitem
Does Installing Blas/Atlas/Mkl/Openblas Will Speed Up R Package That Is Written in C/C++
Replace Missing Values with a Value from Another Column
How to Merge Two Data Frames in R by a Common Column with Mismatched Date/Time Values
Categorical Scatter Plot with Mean Segments Using Ggplot2 in R
How to Access the Name of the Variable Assigned to the Result of a Function Within the Function