0

I want to do a simple replace in R for the following column:

df

                                                                        Songs
1                                                      Saga (Skit) [feat. RZA
2                                                                     Revenge
3                                                           Whatever You Want
4                                                               What About Us
5                                                              But We Lost It
6                                                                     Barbies

I want to do two different replacements:

1) Replace "[" with blank

2) Replace "]" with blank

Need to do this separately though because some of my values only has 1 on the brackets like the first value in the Songs column.

df[,1]<-gsub("[","",df[,1])

Error:

Error in gsub("[", "", newdf2[, 1]) : 
  invalid regular expression '[', reason 'Missing ']''

How do I go about going around this invalid regular expression error?

Thanks!

nak5120
  • 4,089
  • 4
  • 35
  • 94
  • @Henrik apologies, didn't see the other question. Bryan Goggin and akrun were helpful though in giving a different way of solving it. Thanks – nak5120 Oct 13 '17 at 19:23

2 Answers2

2

The [ is a metacharacter, so it needs to be escaped

gsub("\\[|\\]", "", df$Songs)

Or other way is

gsub("[][]", "", df$Songs)
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Sometimes you have to double escape things in R. This should work to do both the replacements in one go.

gsub("\\[|\\]", "", df$Songs)
Bryan Goggin
  • 2,449
  • 15
  • 17