1

This may be a silly question, but its doing my head in. I have always used gsub, but for some reason, it isnt working for this one:

Example of dataset

ColumnS
I 2,[3],4:i:-
I 2,[3],4:i:-
I 2,[3],4:b:-
Give
Derby
Panama
Kentucky

This is what I've been trying

dataset$ColumnS<-gsub("I 2,[3],4","2,[3],4", dataset$ColumnS)

What is wrong with it?

cms72
  • 177
  • 10
  • 2
    You need to escape the square brackets or add `fixed = TRUE`. Try `gsub("I 2,[3],4:", "2,3,4", 'I 2,[3],4:i:-', fixed = TRUE)` – Sotos Jul 24 '19 at 09:23
  • Possible duplicate of [How do I deal with special characters like \^$.?\*|+()\[{ in my regex?](https://stackoverflow.com/questions/27721008/how-do-i-deal-with-special-characters-like-in-my-regex) – jay.sf Jul 24 '19 at 10:00
  • Thank you Sotos! the fixed=TRUE worked! – cms72 Jul 24 '19 at 10:36

1 Answers1

0

Square brackets are special characters when it comes to pattern recognition and if you want to match them, you have to use escape characters to inform R.

dataset$ColumnS <- gsub("I 2,\\[3\\],4","2,[3],4", dataset$ColumnS)

You can also use the argument fixed=TRUE which will take the pattern as a string.

dataset$ColumnS <- gsub("I 2,[3],4","2,[3],4", dataset$ColumnS, fixed=TRUE)

Arienrhod
  • 2,451
  • 1
  • 11
  • 19