I'm new to R and am stuck with backreferencing that doesn't seem to work. In:
gsub("\\((\\d+)\\)", f("\\1"), string)
It correctly grabs the number in between parentheses but doesn't apply the (correctly defined, working otherwise) function f to replace the number --> it's actually the string "\1" that passes through to f.
Am I missing something or is it just that R does not handle this? If so, any idea how I could do something similar, i.e. applying a function "on the fly" to the (actually many) numbers that occur in between parentheses in the text I'm parsing?
Thanks a lot for your help.
This is for multiple different replacements.
R does not have the option of applying a function directly to a match via
gsub
. You'll actually have to extract the match, transform the value, then replace the value. This is relativaly easy with theregmatches
function. For exampleOf course you can make
f
do whatever you like just make sure it's vector-friendly. Of course, you could wrap this in your own functionNote that in these examples we're not using a capture group, we're just grabbing the entire match. There are ways to extract the capture groups but they are a bit messier. If you wanted to provide an example where such an extraction is required, I might be able to come up with something fancier.