我想用千位分隔符格式化数字并指定小数位数.我知道如何分开做这些,但不能一起做.
比如,我用format每本为小数:
FormatDecimal <- function(x, k) {
return(format(round(as.numeric(x), k), nsmall=k))
}
FormatDecimal(1000.64, 1) # 1000.6
Run Code Online (Sandbox Code Playgroud)
对于千位分隔符,formatC:
formatC(1000.64, big.mark=",") # 1,001
Run Code Online (Sandbox Code Playgroud)
但这些并不能很好地融合在一起:
formatC(FormatDecimal(1000.64, 1), big.mark=",")
# 1000.6, since no longer numeric
formatC(round(as.numeric(1000.64), 1), nsmall=1, big.mark=",")
# Error: unused argument (nsmall=1)
Run Code Online (Sandbox Code Playgroud)
我该怎么1,000.6办?
编辑:这不同于这个问题,询问格式3.14为3,14(被标记为可能的重复).
Max*_*nis 60
format不是formatC:
format(round(as.numeric(1000.64), 1), nsmall=1, big.mark=",") # 1,000.6
LMc*_*LMc 14
该scales包有一个label_comma功能:
scales::label_comma(accuracy = .1)(1000.64)
[1] "1,000.6"
Run Code Online (Sandbox Code Playgroud)
如果您想在千位中使用逗号以外的其他字符或其他字符而不是小数点等(请参见下文),请使用附加参数。
注意: 的输出label_comma(...)是一个函数,以便更容易在ggplot2参数中使用,因此需要附加括号符号。如果您重复使用相同的格式,这可能会很有帮助:
my_comma <- scales::label_comma(accuracy = .1, big.mark = ".", decimal.mark = ",")
my_comma(1000.64)
[1] "1.000,6"
my_comma(c(1000.64, 1234.56))
[1] "1.000,6" "1.234,6"
Run Code Online (Sandbox Code Playgroud)
小智 12
formatC(1000.64, format="f", big.mark=",", digits=1)
Run Code Online (Sandbox Code Playgroud)
(对不起,如果我错过了什么.)
formattable提供comma:
library(formattable)
comma(1000.64, digits = 1) # 1,000.6
Run Code Online (Sandbox Code Playgroud)
comma提供了一个基本的接口formatC。
| 归档时间: |
|
| 查看次数: |
36992 次 |
| 最近记录: |