anu
anu

Reputation: 295

Removing curly brackets in R

How to remove curly brackets in R? Eg. "{abcd}" to "abcd"

How can I use gsub function in R to do this? If any other method is available, please suggest.

Upvotes: 5

Views: 8368

Answers (3)

SeGa
SeGa

Reputation: 9809

I tend to do it in 2 steps with the argument fixed = TRUE, which will speed up things quite a bit.

x <- "{abcd}"
res1 = gsub("{", "", x, fixed = TRUE)
res1 = gsub("}", "", res1, fixed = TRUE)

and some benchmarks will tell you thats it about twice as fast:

mc = microbenchmark::microbenchmark(times = 300,
  a={
    gsub("\\{|\\}", "", x)
  },
  b = {
    gsub("[{}]", "", x)
  },
  c = {
    gsub("^\\{+(.+)\\}+$", '\\1', x)
  },
  d = {
    res2 = gsub("{", "", x, fixed = TRUE)
    gsub("}", "", res2, fixed = TRUE)
  }
)
mc
Unit: microseconds
    expr   min    lq     mean median    uq    max neval
    a 5.120 5.121 5.864220 5.6900 5.690 18.774   300
    b 5.120 5.121 5.947683 5.6900 5.690 21.050   300
    c 6.827 7.112 8.027910 7.3965 7.965 35.841   300
    d 1.707 2.277 2.877600 2.8450 2.846 14.223   300

Upvotes: 0

Matthew Plourde
Matthew Plourde

Reputation: 44614

x <- "{abcd}"
gsub("^\\{+(.+)\\}+$", '\\1', x)

This will remove all braces on either end of the string. The difference between this and @Dickoa's answer is that this would leave any braces inside the string alone.

Upvotes: 4

dickoa
dickoa

Reputation: 18437

Try this

gsub("\\{|\\}", "", "{abcd}")
[1] "abcd"

Or this

gsub("[{}]", "", "{abcd}")

Upvotes: 12

Related Questions