36

I have a character vector in which each element is enclosed in brackets. I want to remove the brackets and just have the string.

So I tried:

n = c("[Dave]", "[Tony]", "[Sara]")

paste("", n, "", sep="")

Unfortunately, this doesn't work for some reason.

I've performed the same task before using this same code, and am not sure why it's not working this time.

I want to go from '[Dave]' to 'Dave'.

What am I doing wrong?

zx8754
  • 52,746
  • 12
  • 114
  • 209
ATMathew
  • 12,566
  • 26
  • 69
  • 76

4 Answers4

72

You could gsub out the brackets like so:

n = c("[Dave]", "[Tony]", "[Sara]")

gsub("\\[|\\]", "", n)
[1] "Dave" "Tony" "Sara"
danpelota
  • 2,245
  • 1
  • 20
  • 17
13

A regular expression substitution will do it. Look at the gsub() function.

This gives you what you want (it removes any instance of '[' or ']'):

gsub("\\[|\\]", "", n)
dan
  • 355
  • 1
  • 7
  • @boulder_ruby it is input character vector. – zx8754 Dec 11 '18 at 14:49
  • 1
    @zx8754 6 years later! Yes, I agree, it is a variable. July 2012 I was just getting started learning ruby (and later, rails) at the davinci coding boot camp in Louisville, CO just outside of Boulder. The inaugural class! Wonder what those guys are doing now... – boulder_ruby Dec 27 '18 at 14:59
  • @boulder_ruby sorry, my reply was mainly to other users having the same question, no offence. – zx8754 Dec 27 '18 at 21:54
8

If working within tidyverse:

library(tidyverse); library(stringr)

n = c("[Dave]", "[Tony]", "[Sara]")

n %>% str_replace_all("\\[|\\]", "")
[1] "Dave" "Tony" "Sara"
Irakli
  • 959
  • 1
  • 11
  • 18
8

The other answers should be enough to get your desired output. I just wanted to provide a brief explanation of why what you tried didn't work.

paste concatenates character strings. If you paste an empty character string, "", to something with a separator that is also an empty character string, you really haven't altered anything. So paste can't make a character string shorter; the result will either be the same (as in your example) or longer.

joran
  • 169,992
  • 32
  • 429
  • 468