Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

str_replace to a particular position

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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?

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading