Home > Blockchain >  R: Remove string from within another string?
R: Remove string from within another string?

Time:11-23

I have data that looks like

Var1
----------------------
text 1 (str to remove)
----------------------
text 2 (str to remove)
----------------------
text 3 (str to remove)
----------------------

I want to remove

" (str to remove)" 

So that the output looks like

Var1
----------------------
text 1
----------------------
text 2
----------------------
text 3
----------------------

I have tried gsub and str_replace but I guess they only work with regex patterns?

CodePudding user response:

We match one or more spaces (\\s ) followed by the ( and the rest of the characters (.*) and replace with blank for the 'Var1' column and assign back to the data

df1$Var1 <- sub("\\s \\(.*", "", df1$Var1)

If the string is fixed, then we can also do

df1$Var1 <- sub(" (str to remove)", "", df1$Var1, fixed = TRUE)

data

df1 <- structure(list(Var1 = c("text 1 (str to remove)", 
"text 2 (str to remove)", 
"text 3 (str to remove)")), class = "data.frame",
 row.names = c(NA, 
-3L))
  • Related