Jor*_*eys 118
您可以尝试format或prettyNum,但这两个函数都返回一个字符向量.我只用它来打印.
> prettyNum(12345.678,big.mark=",",scientific=FALSE)
[1] "12,345.68"
> format(12345.678,big.mark=",",scientific=FALSE)
[1] "12,345.68"
Run Code Online (Sandbox Code Playgroud)
编辑:正如Michael Chirico在评论中所说:
请注意,这些具有用空格填充打印字符串的副作用,例如:
> prettyNum(c(123,1234),big.mark=",")
[1] " 123" "1,234"
Run Code Online (Sandbox Code Playgroud)
添加trim=TRUE
到format
或preserve.width="none"
以prettyNum
防止这种情况:
> prettyNum(c(123,1234),big.mark=",", preserve.width="none")
[1] "123" "1,234"
> format(c(123,1234),big.mark=",", trim=TRUE)
[1] "123" "1,234"
Run Code Online (Sandbox Code Playgroud)
Dir*_*tel 30
见?format
:
> format(1e6, big.mark=",", scientific=FALSE)
[1] "1,000,000"
>
Run Code Online (Sandbox Code Playgroud)
Mat*_*ewR 10
发布的其他答案显然有效 - 但我一直都在使用
library(scales)
comma_format()(1000000)
Run Code Online (Sandbox Code Playgroud)
我认为 Joe 对 MatthewR 的评论提供了最好的答案,应该强调:
截至 2018 年 9 月,该scales
包( 的一部分Tidyverse
)正是这样做的:
> library(scales)
> x <- 10e5
> comma(x)
[1] "1,000,000"
Run Code Online (Sandbox Code Playgroud)
该scales
包似乎与 配合得很好ggplot2
,允许精细控制数字在图形和图表中的显示方式。