I want to replace all number range by their mean. For example:
DT <- data.table(raw.data = c("1-2 min", "3-5 min or 2-4 min"),
desirable.data = c("1.5 min", "4 min or 3 min"))
Now, I can do this by
gsubfn(pattern = "(\\d+)(-)(\\d+)", ~ mean(c(as.numeric(..1), as.numeric(..3))), x = DT$raw.data)
Still, I'm wondering if there is a better solution. Because this approach returned an error "Variable '1' is not found in calling scope." when used in data.table, thanks!
More generally speaking, when I tried to replace certain part of the string by regex, I wanted to replace the "match" part according to the "group", rather than just some known string. But it seemed that functions like str_replace_all doesn't work this way. The argument "replacement" only allow some string as input.
Update
DT[, new := gsubfn(pattern = "(\\d+)(-)(\\d+)",
~ mean(c(as.numeric(..1), as.numeric(..3))),
x = raw.data)]
When trying to use gsubfn in data.table, there's an error:
Error in [.data.table(DT, , :=(new, gsubfn(pattern = "(\\d+)(-)(\\d+)", :
Variable '1' is not found in calling scope. Looking in calling scope because this symbol was prefixed with .. in the j= parameter.