1

I get distorted output when I try to replace the question mark symbol by the digit zero. Given below my code.

x <- c(2,3,"m","M","b","?")
x1 <- gsub("m|M","6",x)
x1
#[1] "2" "3" "6" "6" "b" "?"
x1 <- gsub("?","0",x)
x1
#[1] "020" "030" "0m0" "0M0" "0b0" "0?0"

Anybody have any idea why this happens? Any help would be appreciated.

markus
  • 25,843
  • 5
  • 39
  • 58
008
  • 107
  • 7

1 Answers1

2

The ? is a metacharacter, we need to escape ("\?") or place it inside square brackets

gsub("[?]", "0", x1)

Or use fixed = TRUE

gsub("?", "0", x1, fixed = TRUE)
akrun
  • 874,273
  • 37
  • 540
  • 662