Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

r - Convert numbers to SI prefix

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

10 -> 10
1000 -> 1K
0.01 - > 10m

etc ... I can do it myself but I would prefer to not reinvent the wheel.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
require(sitools)
f2si(80000)
 [1] "80 k"
f2si(8E12)
 [1] "8 T"

It seems to be very simplistic as it appends two spaces if no SI prefix is used:

f2si(80)
[1] "80  "

The function is easy to modify to include rounding. I also fixed the issue with appended spaces.

f2si2<-function (number,rounding=F) 
{
    lut <- c(1e-24, 1e-21, 1e-18, 1e-15, 1e-12, 1e-09, 1e-06, 
        0.001, 1, 1000, 1e+06, 1e+09, 1e+12, 1e+15, 1e+18, 1e+21, 
        1e+24)
    pre <- c("y", "z", "a", "f", "p", "n", "u", "m", "", "k", 
        "M", "G", "T", "P", "E", "Z", "Y")
    ix <- findInterval(number, lut)
    if (lut[ix]!=1) {
        if (rounding==T) {
         sistring <- paste(round(number/lut[ix]), pre[ix])
        }
        else {
         sistring <- paste(number/lut[ix], pre[ix])
        } 
    }
    else {
        sistring <- as.character(number)
    }
    return(sistring)
}

f2si2(12345)
 [1] "12.345 k"
f2si2(12345,T)
 [1] "12 k"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...