Convert numbers to SI prefix

前端 未结 5 733
温柔的废话
温柔的废话 2020-12-01 13:01

Is there a R function (or any package) allowing to format numbers (integer) using standard unit prefix (Kilo, Mega etc ...), so

10 -> 10
100 -> 1K
0.01         


        
5条回答
  •  鱼传尺愫
    2020-12-01 13:45

    I was looking for Thousand(K), million(M) and Billion(B) number converter. I modified this routine to take a numeric vector/single number spitting out the required output.

    CurrencyFormat <-function (number,rounding=F) 
    {
        first <- TRUE
        lut <- c( 1, 1000, 1000000, 1000000000,1000000000000 )
        pre <- c("", "K", "M", "B", "T")
        if (length(number) > 1) {
            for (cnt in 1:length(number)){        
                ix <- findInterval(number[cnt], lut)
                if (ix != 0 | ix != 1){
                    if (rounding==T) {
                        sistring <- paste(round(number[cnt]/lut[ix]), pre[ix])
                    }
                    else {
                        sistring <- paste(signif(number[cnt]/lut[ix],digits=5), pre[ix])
                    }
                    if (first){
                        tnumber <- sistring
                        fnumber <- tnumber
                        first <- FALSE
                    }
                    else
                        fnumber <- append(fnumber, sistring)
                }
                else {
                    sistring <- number[cnt]
                    if (first){
                        tnumber <- sistring
                        fnumber <- tnumber
                        first <- FALSE
                    }
                    else
                        fnumber <- append(fnumber, sistring)
                }
            }
            return(fnumber)
        }
        else{
            ix <- findInterval(number, lut)
            if (ix != 0 | ix != 1){
                if (rounding==T) {
                    sistring <- paste(round(number/lut[ix]), pre[ix])
                }
                else {
                    sistring <- paste(signif(number/lut[ix],digits=5), pre[ix])
                }
                return(sistring)
            }    
            else
                return(number)
        }
    }
    

    Examples:

    CurrencyFormat(1.25,F)
    [1] "1.25 "
    
    CurrencyFormat(1000.25,F)
    [1] "1.0002 K"
    
    CurrencyFormat(c( 1,45,1234, 4.36e+06, 2.84e+04, 2.01e+06),F)
    [1] "1 "      "45 "     "1.234 K" "4.36 M"  "28.4 K"  "2.01 M" 
    

提交回复
热议问题