R 自定义数字格式:千、百万、十亿

R Custom Number Format: Thousands, Millions, Billions

我正在寻找一种方法来轻松地将我的数字格式化为整个文档中的字符串,从看起来像 21309809 的基本数字到像 2130 万这样更清晰的数字,四舍五入以更正小数。

我正在尝试找到一种方法来格式化千位逗号 (999,999)、百万位小数点 (9.9 M) 和十亿位小数点 (9.9 B)。

即在我的降价文件中有多个实例,我需要根据某些公式在文本中自动执行此操作。 现在,以下内容: Today, there were `r sum_value` new figures returns 为 Today, there were 21309809 new figures 但我希望它自动显示为 Today, there were 21.3 M new figures,并在数字下降到阈值以上或以下时自动调整。

您可以创建自定义数字格式函数。这是我在脚本开头使用的一个。

# Create your function
custom_number_format <- function(x){ifelse(x > 999999999,
                                       paste(format(round((x/1000000000), 2), 
                                                    nsmall=1, big.mark=","), "B"),
                                       ifelse(x > 999999, 
                                       paste(format(round((x/1000000), 1), 
                                                    nsmall=1, big.mark=","),"M"), 
                                       format(round(x), nsmall=0, big.mark=",")))}

# Now try it out
custom_number_format(999)
custom_number_format(999999)
custom_number_format(1000000)
custom_number_format(999900000)
custom_number_format(1000000000)

然后你可以在整个 Markdown 文件中加入 custom_number_format,它会 return 正确的结果。