rregexvectorizationqdap

Can't seem to get vectorized gsub to work with library "qdap" and mgsub


I was looking at this question:

R: gsub, pattern = vector and replacement = vector

I am trying a simple example and I can't get it to work.

testList <- c("apple", "orange", "banana1", "apple4", "orange 8", "banana 10")

repl <- c("apple", "orange", "banana")

pat <- paste0("^", repl, "[[:space:]]*[[:digit:]]*$")

result <- mgsub(pat, repl, testList)

Shouldn't this output:

"apple", "orange", "banana", "apple", "orange", "banana"

Solution

  • You need to specify fixed = FALSE, the default is TRUE, which replaces the pattern as is and doesn't use regex:

    result <- mgsub(pat, repl, testList, fixed = FALSE)
    result
    # [1] "apple"  "orange" "banana" "apple"  "orange" "banana"