Reputation: 1009
How can I use a variable value and a regex position expression together in R? For example, in the following code, how would I replace only cases of "zzz" that come at the start or end of a string? This works for all values of "zzz"
target_nos <- c("1","2","zzz","4")
sample_text <- cbind("1 dog 1","3 cats zzz","zzz foo 1")
for (i in 1:length(target_nos))
{
sample_text <- gsub(pattern = target_nos[i],replacement = "REPLACED", x =
sample_text)
}
But how would I include the ^ and $ position markers? This throws an error
sample_text <- gsub(pattern = ^target_nos[1],replacement = "REPLACED", x =
sample_text)
This runs, but interprets the variable literally, rather than calling the value
sample_text <- gsub(pattern = "^target_nos[1]", replacement = "REPLACED", x =
sample_text)
Upvotes: 2
Views: 1852
Reputation: 23976
You need the ^
and $
characters to be within the regex pattern strings. In other words, target_nos
could be this:
"^1" "^2" "^zzz" "^4" "1$" "2$" "zzz$" "4$"
To build that programmatically from what you've got, you could do this:
target_nos <- c("1","2","zzz","4")
target_nos <- c(paste0('^', target_nos), paste0(target_nos, '$'))
Upvotes: 2