I am trying to clean a variable about income that comes from an historical database. I would like to replace all "£" for "pounds" but placing it after the number. For example "About £500 per annum" --> "About 500 pounds per annum".
I could easily do the first part with:
stringr::str_replace_all("About £500 per annum" ,"£", "pounds")
[1] "About pounds500 per annum"
But I have not been able to place it after the number, which would be important as other input cases might take the form:
"About 200 pounds 0s 0d", "124.21.0", "124 acres let at £140 including a rent charge of £30"
Does anybody know elegant way to do it?
CodePudding user response:
I added the dot as well, to convert £30.00 to 30.00 pounds. So with gsub we catch £ (would be \1) and followed by the amount (\2). The replacement will be the numeric catch followed by the word pounds.
v <- c("About 200 pounds 0s 0d", "124.21.0", "124 acres let at £140 including a rent charge of £30.00")
gsub("(£)([0-9\\.] )", "\\2 pounds", v)
# [1] "About 200 pounds 0s 0d"
# [2] "124.21.0"
# [3] "124 acres let at 140 pounds including a rent charge of 30.00 pounds"
CodePudding user response:
You could use a capture group here:
library(stringr)
x <- "About £500 per annum"
str_replace_all(x, "£(\\d (?:\\.\\d )?)", "\\1 pounds")
[1] "About 500 pounds per annum"
