将数字转换为 SI 前缀 [英] Convert numbers to SI prefix

查看:73
本文介绍了将数字转换为 SI 前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 R 函数(或任何包)允许使用标准单位前缀(Kilo、Mega 等...)格式化数字(整数),所以

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 - > 10m

等等...我可以自己做,但我不想重新发明轮子.

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

推荐答案

require(sitools)
f2si(80000)
 [1] "80 k"
f2si(8E12)
 [1] "8 T"

这似乎很简单,因为如果没有使用 SI 前缀,它会附加两个空格:

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"

这篇关于将数字转换为 SI 前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆