R: gsub of exact full string with fixed = T

1.4k views Asked by At

I am trying to gsub exact FULL string - I know I need to use ^ and $. The problem is that I have special characters in strings (could be [, or .) so I need to use fixed=T. This overrides the ^ and $. Any solution is appreciated. Need to replace 1st, 2nd element in exact_orig with 1st, 2nd element from exact_change but only if full string is matched from beginning to end.

exact_orig = c("oz","32 oz")
exact_change = c("20 oz","32 ct")

gsub_FixedTrue <- function(i) {
  for(k in seq_along(exact_orig)) i = gsub(exact_orig[k],exact_change[k],i,fixed=TRUE)
  return(i)
}

Test cases:

print(gsub_FixedTrue("32 oz")) #gives me "32 20 oz" - wrong! Must be "32 ct"
print(gsub_FixedTrue("oz oz")) # gives me "20 oz 20 oz" - wrong! Must remain as "oz oz"

I read a somewhat similar thread, but could not make it work for full string (grep at the beginning of the string with fixed =T in R?)

1

There are 1 answers

5
MrFlick On BEST ANSWER

If you want to exactly match full strings, i don't think you really want to use regular expressions in this case. How about just the match() function

fixedTrue<-function(x) {
    m <- match(x, exact_orig)
    x[!is.na(m)] <- exact_change[m[!is.na(m)]]
    x
}

fixedTrue(c("32 oz","oz oz"))
# [1] "32 ct" "oz oz"