我想知道如何用R工作。这意味着,算术,打印格式良好的数字等。
例如我有一些值
1.222.333,37
1.223.444,88
我可以将它翻译成数字并将其舍入,除去分数,但没有更好的模式可以使用?我确实尝试过格式化方法,例如:
format(141103177058,digits=3,small.interval=3,decimal.mark='.',small.mark=',')
但没有成功。任何提示或想法?
答案 0 :(得分:6)
scale包具有以下功能: dollar_format()
install.packages("scales")
library(scales)
muchoBucks <- 15558.5985121
dollar_format()(muchoBucks)
[1] "$15,558.60"
答案 1 :(得分:4)
假设我们有两个特定的字符值(货币):
s1 <- "1.222.333,37"
s2 <- "1.223.444,88"
首先,我们希望R显示具有正确位数的数值:
# controls representation of numeric values
options(digits=10)
将货币转换为数字可以像这样实现:
# where s is character
moneyToDouble <- function(s){
as.double(gsub("[,]", ".", gsub("[.]", "", s)))
}
x <- moneyToDouble(s1) + moneyToDouble(s2)
x
将数字打印为货币:
# where x is numeric
printMoney <- function(x){
format(x, digits=10, nsmall=2, decimal.mark=",", big.mark=".")
}
printMoney(x)
答案 2 :(得分:4)
这个怎么样:
printCurrency <- function(value, currency.sym="$", digits=2, sep=",", decimal=".") {
paste(
currency.sym,
formatC(value, format = "f", big.mark = sep, digits=digits, decimal.mark=decimal),
sep=""
)
}
printCurrency(123123.334)