[英]regex pattern a few numbers followed by the letter “k”
I would like to replace k in a string with 000. For instance, I want to make "£50000" from "£50k". 我想用000替换字符串中的k。例如,我想从“£50k”中赚取“£50000”。 Note that the function can be applied to cases like "£50k king", which should result in "£50000 king".
请注意,该功能可以应用于“£50k king”这样的情况,这将导致“£50000 king”。
Here's what I have so far: 这是我到目前为止所拥有的:
replace_k = function(data){
data = gsub("^[0-9]k", "[0-9]000", data)
return(data)
}
怎么样
data = gsub("([0-9]+)k", "\\1000", data)
You may use the following solution to handle K
, M
and G
(and more if you want, just adjust the ToDigits
function): 您可以使用以下解决方案来处理
K
, M
和G
(如果需要,可以使用更多,只需调整ToDigits
函数):
> 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, .
在这里,
(\\\\d*\\\\.?\\\\d+)([KMG])
捕获0+位数, .
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.) 并且1+数字进入第1组,然后
K
或M
或G
进入第2组, gsubfn
用于操纵找到的匹配,使得找到的数字与使用简单助手ToDigits
函数获得的正确值ToDigits
(如果K
在第2组中,乘以1000
,等等。)
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.