R에서 숫자를 백분율로 포맷하는 방법은 무엇입니까?
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
, 나는 R.베이스에 적절히 편리한 래퍼 찾을 아직 ??"percent"
아무것도 유용 양보하지 않았다입니다. library(sos); findFn("format percent")
1250 적중을 반환하므로 다시 유용하지 않습니다. ggplot2
기능이 percent
있지만 반올림 정확도를 제어 할 수 없습니다.
몇 년 후 업데이트 :
요즘에는 krlmlr의 답변에 설명 된대로 패키지에 percent
기능이 scales
있습니다. 내 수동 솔루션 대신 사용하십시오.
같은 것을 시도하십시오
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"
.
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%"
패키지 에서 percent
기능을 확인하십시오 formattable
.
library(formattable)
x <- c(0.23, 0.95, 0.3)
percent(x)
[1] 23.00% 95.00% 30.00%
좀이 답변에 속도를 벤치마킹 및보고 놀랐다했다 percent
에서 scales
의 부진 주어진, 그래서 선전 패키지. 적절한 형식 지정을위한 자동 검출기라는 이점이 있다고 생각하지만 데이터가 어떻게 보이는지 알면 피하는 것이 분명합니다.
Here are the results from trying to format a list of 100,000 percentages in (0,1) to a percentage in 2 digits:
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()
So sprintf
emerges as a clear winner when we want to add a percent sign. On the other hand, if we only want to multiply the number and round (go from proportion to percent without "%", then round()
is fastest:
# 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()
Here's my solution for defining a new function (mostly so I can play around with Curry and Compose :-) ):
library(roxygen)
printpct <- Compose(function(x) x*100, Curry(sprintf,fmt="%1.2f%%"))
You can use the scales package just for this operation (without loading it with require or library)
scales::percent(m)
Seeing how scalable::percent
had already been shown to be slowest and Liliana Pacheco offering up another solution, I went ahead and tried to benchmark it against some of the other options based on the example Michael set:
library(microbenchmark)
library(scales)
library(formattable)
x<-runif(1e5)
lilip <- function() formattable::percent(x,2)
krlmlr <- function() scales::percent(x)
andrie1 <- function() paste0(round(x,4) * 100, '%')
microbenchmark(times=100L,lilip(), krlmlr(), andrie1())
These are the results I got:
Unit: microseconds
expr min lq mean median uq max neval
lilip() 194.562 373.7335 772.5663 889.7045 950.4035 1611.537 100
krlmlr() 226270.845 237985.6560 260194.9269 251581.0235 280704.2320 373022.180 100
andrie1() 87916.021 90437.4820 92791.8923 92636.8420 94448.7040 102543.252 100
I have no idea, though, why my krlmlr()
and andrie1()
performed so much worse than in MichaelChirico's example. Any clues?
try this~
data_format <- function(data,digit=2,type='%'){
if(type=='d') {
type = 'f';
digit = 0;
}
switch(type,
'%' = {format <- paste("%.", digit, "f%", type, sep='');num <- 100},
'f' = {format <- paste("%.", digit, type, sep='');num <- 1},
cat(type, "is not a recognized type\n")
)
sprintf(format, num * data)
}
This function could transform the data to percentages by columns
percent.colmns = function(base, columnas = 1:ncol(base), filas = 1:nrow(base)){
base2 = base
for(j in columnas){
suma.c = sum(base[,j])
for(i in filas){
base2[i,j] = base[i,j]*100/suma.c
}
}
return(base2)
}
참고URL : https://stackoverflow.com/questions/7145826/how-to-format-a-number-as-percentage-in-r
'IT story' 카테고리의 다른 글
HashMap get / put 복잡성 (0) | 2020.07.21 |
---|---|
JavaScript에 유니 코드 문자 삽입 (0) | 2020.07.21 |
C # 생성자 실행 순서 (0) | 2020.07.21 |
LINQ OrderBy와 ThenBy (0) | 2020.07.20 |
언제 UseShellExecute를 True로 설정해야합니까? (0) | 2020.07.20 |