3 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
幾年后的更新:
這些天percent,scales軟件包中已經(jīng)有一個(gè)功能,如krlmlr的答案所述。使用它代替我的手動(dòng)解決方案。
嘗試類似
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)
(如果您愿意,請(qǐng)將格式從更改"f"為"g"。)

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
簽出scales包裝。ggplot2我認(rèn)為它曾經(jīng)是的一部分。
library('scales')
percent((1:10) / 100)
# [1] "1%" "2%" "3%" "4%" "5%" "6%" "7%" "8%" "9%" "10%"
在大多數(shù)情況下,用于檢測(cè)精度的內(nèi)置邏輯應(yīng)該可以很好地工作。
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%"

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊
我做了一些基準(zhǔn)測(cè)試對(duì)這些問題的答案的速度和驚訝地看到percent在scales如此吹捧包裝,鑒于其疲弱。我想它的優(yōu)勢(shì)是它的自動(dòng)檢測(cè)器可以正確格式化,但是如果您知道數(shù)據(jù)看起來像什么,那么顯然可以避免。
以下是嘗試將(0,1)中的100,000個(gè)百分比的列表格式設(shè)置為2位數(shù)字的百分比的結(jié)果:
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,當(dāng)我們要添加百分號(hào)時(shí),它將成為明顯的贏家。另一方面,如果我們只想將數(shù)字乘以四舍五入(從比例乘以百分比而沒有“%”,則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()
- 3 回答
- 0 關(guān)注
- 3543 瀏覽
添加回答
舉報(bào)