【问题标题】:How to round up percentage in 0 decimal in R如何在R中以0小数舍入百分比
【发布时间】:2019-05-10 05:59:04
【问题描述】:

寻找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 一样简单的小数百分比调整包?

【问题讨论】:

  • @Marius - 甚至 sprintf("%.0f%%", d * 100) - 如果你想要 0 位小数,你必须要求它。

标签: r format decimal rounding percentage


【解决方案1】:

我建议您先查看?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.

【讨论】:

  • 是的,但是在发布问题之前我遇到了这个错误:percent(d, 1) Error in percent(d, 1) : unused argument (1)
  • 也许您正在使用另一个包中的percent 函数?或者你有一个旧版本的scales?查看软件包新闻,看起来accuracy 参数是在 1.0 版中引入的。正如我在答案中显示的那样,对我来说效果很好。
  • 谢谢 Gregor,我想我应该检查一下 scales 的版本
【解决方案2】:

使用roundpaste

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

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

【讨论】:

    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2022-01-26
    相关资源
    最近更新 更多