我正在尝试将货币值从系数转换为数字。格式为1.105亿欧元,56.5万欧元,我可以摆脱欧元符号,M和K字母,但我还需要进行转换,以显示110.5M=110.500.000
和565K=565.000
。有什么建议的方法吗?
value<-as.numeric(gsub("[€MK]", "", as.character(strength[1:18207,1])))
要转换的数据
€110.5M €565K
€77M €405K
€118.5M €290K
答案 0 :(得分:1)
一个选项是gsubfn
library(gsubfn)
out <- unname(sapply(gsubfn("M|K", list(M = "* 1e6", K = "* 1e3"),
sub("€", "", str1)), function(x) eval(parse(text = x))))
out
#[1] 110500000 565000 77000000 405000 118500000 290000
scales::dollar_format(prefix = "", big.mark = ".")(out)
#[1] "110.500.000" "565.000" "77.000.000" "405.000"
#[4] "118.500.000" "290.000"
str1 <- c("€110.5M", "€565K", "€77M", "€405K", "€118.5M", "€290K")
答案 1 :(得分:1)
以下是使用sub
的基本R选项:
input <- c("€110.5M", "€565K")
exp <- sapply(input, function(x) sub("€(\\d+(?:\\.\\d+)?)K", "\\1*1000",
sub("€(\\d+(?:\\.\\d+)?)M", "\\1*1000000", x)))
exp
sapply(exp, function(x) eval(parse(text=x)))
€110.5M €565K
"110.5*1000000" "565*1000"
€110.5M €565K
110500000 565000