I would like to replace k in a string with 000. For instance, I want to make \"£50000\" from \"£50k\". Note that the function can be applied to cases like \"£50k king\", which s
You may use the following solution to handle K
, M
and G
(and more if you want, just adjust the ToDigits
function):
> library(gsubfn)
> x <- "0.56K 50K 1.5M 56.56G"
> ToDigits <- function(s) {ifelse(s=="K", 1000, ifelse(s=="M", 1000000, 1000000000)) }
> gsubfn("(\\d*\\.?\\d+)([KMG])", function(y,z) as.numeric(y) * ToDigits(z), x)
[1] "560 50000 1500000 5.656e+10"
Here, (\\d*\\.?\\d+)([KMG])
captures 0+ digits, .
and 1+ digits into Group 1 and then K
or M
or G
into Group 2, and gsubfn
is used to manipulate the found match in such a way that the found number is multipled with the right value obtained using a simple helper ToDigits
function (if K
is in Group 2, multiply with 1000
, etc.)
To make it case insensitive, you may tweak the code above as
> ToDigits <- function(s) {ifelse(tolower(s)=="k", 1000, ifelse(tolower(s)=="m", 1000000, 1000000000)) }
> gsubfn("(\\d*\\.?\\d+)([KMGkmg])", function(y,z) as.numeric(y) * ToDigits(z), x)
[1] "560 50000 1500000 5.656e+10"
How about
data = gsub("([0-9]+)k", "\\1000", data)