作为 R 的新手,曾经让我感到困惑的一件事是如何将数字格式化为用于打印的百分比。
例如,将 0.12345
显示为 12.345%
。我有很多解决方法,但这些似乎都不是“对新手友好的”。例如:
set.seed(1)
m <- runif(5)
paste(round(100*m, 2), "%", sep="")
[1] "26.55%" "37.21%" "57.29%" "90.82%" "20.17%"
sprintf("%1.2f%%", 100*m)
[1] "26.55%" "37.21%" "57.29%" "90.82%" "20.17%"
问题:是否有一个基本的 R 函数可以做到这一点?或者,是否有广泛使用的包提供方便的包装器?
尽管在 ?format
、?formatC
和 ?prettyNum
中搜索了类似的内容,但我还没有在base R. ??"percent"
没有产生任何有用的东西。 库(sos); findFn("format percent")
返回 1250 次点击 - 所以同样没用。 ggplot2
有一个函数 percent
但这不能控制舍入精度。
最佳答案
甚至以后:
正如@DzimitryM 所指出的,percent()
已被“淘汰”,取而代之的是 label_percent()
,它是旧 percent_format 的同义词()
函数。
label_percent()
返回一个函数,所以要使用它,你需要一对额外的括号。
library(scales)
x <- c(-1, 0, 0.1, 0.555555, 1, 100)
label_percent()(x)
## [1] "-100%" "0%" "10%" "56%" "100%" "10 000%"
通过在第一组括号内添加参数来自定义它。
label_percent(big.mark = ",", suffix = " percent")(x)
## [1] "-100 percent" "0 percent" "10 percent"
## [4] "56 percent" "100 percent" "10,000 percent"
几年后的更新:
现在有一个 percent
scales
中的函数包,如 krlmlr 的回答中所述。使用它代替我的手动解决方案。
试试类似的东西
percent <- function(x, digits = 2, format = "f", ...) {
paste0(formatC(100 * x, format = format, digits = digits, ...), "%")
}
有用法,例如,
x <- c(-1, 0, 0.1, 0.555555, 1, 100)
percent(x)
(如果您愿意,请将格式从 "f"
更改为 "g"
。)
https://stackoverflow.com/questions/7145826/