为了账号安全,请及时绑定邮箱和手机立即绑定

如何将数字格式化为R中的百分比?

如何将数字格式化为R中的百分比?

holdtom 2019-12-20 09:53:26
令我困惑的R之一是如何格式化数字以百分比形式打印。例如,显示0.12345为12.345%。我有很多解决方法,但是这些似乎都不是“ newby friendly”。例如: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,我还没有找到合适方便的包装在基地R. ??"percent"没有产生任何有用的东西。 library(sos); findFn("format percent")返回1250次匹配-再次没有用。 ggplot2具有功能,percent但无法控制舍入精度。
查看完整描述

3 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

几年后的更新:


这些天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"。)


查看完整回答
反对 回复 2019-12-20
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

签出scales包装。ggplot2我认为它曾经是的一部分。


library('scales')

percent((1:10) / 100)

#  [1] "1%"  "2%"  "3%"  "4%"  "5%"  "6%"  "7%"  "8%"  "9%"  "10%"

在大多数情况下,用于检测精度的内置逻辑应该可以很好地工作。


percent((1:10) / 1000)

#  [1] "0.1%" "0.2%" "0.3%" "0.4%" "0.5%" "0.6%" "0.7%" "0.8%" "0.9%" "1.0%"

percent((1:10) / 100000)

#  [1] "0.001%" "0.002%" "0.003%" "0.004%" "0.005%" "0.006%" "0.007%" "0.008%"

#  [9] "0.009%" "0.010%"

percent(sqrt(seq(0, 1, by=0.1)))

#  [1] "0%"   "32%"  "45%"  "55%"  "63%"  "71%"  "77%"  "84%"  "89%"  "95%" 

# [11] "100%"

percent(seq(0, 0.1, by=0.01) ** 2)

#  [1] "0.00%" "0.01%" "0.04%" "0.09%" "0.16%" "0.25%" "0.36%" "0.49%" "0.64%"

# [10] "0.81%" "1.00%"


查看完整回答
反对 回复 2019-12-20
?
慕桂英546537

TA贡献1848条经验 获得超10个赞

我做了一些基准测试对这些问题的答案的速度和惊讶地看到percent在scales如此吹捧包装,鉴于其疲弱。我想它的优势是它的自动检测器可以正确格式化,但是如果您知道数据看起来像什么,那么显然可以避免。


以下是尝试将(0,1)中的100,000个百分比的列表格式设置为2位数字的百分比的结果:


library(microbenchmark)

x = runif(1e5)

microbenchmark(times = 100L, andrie1(), andrie2(), richie(), krlmlr())

# Unit: milliseconds

#   expr       min        lq      mean    median        uq       max

# 1 andrie1()  91.08811  95.51952  99.54368  97.39548 102.75665 126.54918 #paste(round())

# 2 andrie2()  43.75678  45.56284  49.20919  47.42042  51.23483  69.10444 #sprintf()

# 3  richie()  79.35606  82.30379  87.29905  84.47743  90.38425 112.22889 #paste(formatC())

# 4  krlmlr() 243.19699 267.74435 304.16202 280.28878 311.41978 534.55904 #scales::percent()

因此sprintf,当我们要添加百分号时,它将成为明显的赢家。另一方面,如果我们只想将数字乘以四舍五入(从比例乘以百分比而没有“%”,则round()最快):


# Unit: milliseconds

#        expr      min        lq      mean    median        uq       max

# 1 andrie1()  4.43576  4.514349  4.583014  4.547911  4.640199  4.939159 # round()

# 2 andrie2() 42.26545 42.462963 43.229595 42.960719 43.642912 47.344517 # sprintf()

# 3  richie() 64.99420 65.872592 67.480730 66.731730 67.950658 96.722691 # formatC()


查看完整回答
反对 回复 2019-12-20
  • 3 回答
  • 0 关注
  • 3295 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信