如何在R中将小数点后0的百分比四舍五入

时间:2019-05-10 05:59:04

标签: r format decimal rounding percentage

寻找一种简单的方法,例如EXCEL“增加小数”,“减少小数”

# Example number
d <- c(0.6199548,0.8884106,0.9030066)

# Expected result :
[1]62% 89% 90%

# library scales result cannot adjust to 0 decimal
percent(d)
[1] "62.0%" "88.8%" "90.3%"

# Cannot handle sprinf() function well as weird result generated like below: 
sprintf("%.1f %%", d)
[1] "0.6 %" "0.9 %" "0.9 %"

我们有简单的程序包来调整R中的EXCEL一样简单的小数百分比吗?

2 个答案:

答案 0 :(得分:5)

使用roundpaste

d <- c(0.6199548,0.8884106,0.9030066)
paste0(round(d*100), "%")

[1] "62%" "89%" "90%"

答案 1 :(得分:4)

建议您在决定?percent可以做什么和不能做什么之前,先阅读它们。

# library scales result cannot adjust to 0 decimal
## OR CAN IT
percent(d, 1)
[1] "62%" "89%" "90%"

从帮助页面?percent

percent(x, accuracy = NULL, scale = 100, prefix = "",
  suffix = "%", big.mark = " ", decimal.mark = ".", trim = TRUE,
  ...)
# ...
# accuracy  Number to round to, NULL for automatic guess.