Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing brackets in a string

I'm trying to trim trailing square brackets, inner quotes and slashes in a list of R strings, preferably using dplyr.

Sample data:

df <- c("['Mamie Smith']", "[\"Screamin' Jay Hawkins\"]")

Expected result:

"Mamie Smith", "Screamin' Jay Hawkins"

What I have tried:

gsub("[[]]", "", df) # Throws error
df %>%
  str_replace("[[]]", "") # Also throws error
like image 952
afrologicinsect Avatar asked Sep 30 '26 16:09

afrologicinsect


1 Answers

In base R we can make use of trimws function:

if we are not interested in the non word parts:

trimws(df, whitespace = "\\W+")
[1] "Mamie Smith"           "Screamin' Jay Hawkins"

But if we are only interested in deleting squarebrackets and quotes while leaving other punctuatons, spaces etc then:

trimws(df, whitespace = "[\\]\\[\"']+")
[1] "Mamie Smith"           "Screamin' Jay Hawkins"
like image 114
KU99 Avatar answered Oct 02 '26 08:10

KU99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!