使用逗号千位分隔符和指定的小数在 R 中格式化数字

Format number in R with both comma thousands separator and specified decimals

我想用千位分隔符和指定小数位数来格式化数字。我知道如何单独做这些,但不知道如何一起做。

例如,我使用 format 每个 this 作为小数:

FormatDecimal <- function(x, k) {
  return(format(round(as.numeric(x), k), nsmall=k))
}
FormatDecimal(1000.64, 1)  # 1000.6

对于千位分隔符,formatC:

formatC(1000.64, big.mark=",")  # 1,001

虽然这些不能很好地结合在一起:

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)

如何获得1,000.6

编辑:这与 不同,后者询问将 3.14 格式化为 3,14(被标记为可能的重复)。

format 不是 formatC:

format(round(as.numeric(1000.64), 1), nsmall=1, big.mark=",") # 1,000.6

formatC(1000.64, format="f", big.mark=",", digits=1)

(抱歉,如果我遗漏了什么。)

formattable 提供 comma:

library(formattable)

comma(1000.64, digits = 1) # 1,000.6

commaformatC 提供基本接口。

scales 库有一个 label_comma 函数:

scales::label_comma(accuracy = .1)(1000.64)
[1] "1,000.6"

如果您想在千位中使用逗号以外的其他内容或其他字符而不是小数点等,则使用其他参数(见下文)。

注意: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"