Convert numbers to SI prefix

前端 未结 5 728
温柔的废话
温柔的废话 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:44

    This is simple to vectorise using case_when from dplyr, and it's much easier on the eyes:

    library(dplyr)
    
    si_number = function(x, digits) {
    
        compress = function(x, n) {
            signif(x * 10^(-n), digits)
        }
    
        case_when(
            x >= 1e6   ~ paste0(compress(x, 6), "M"),
            x >= 1000  ~ paste0(compress(x, 3), "k"),
            x >= 1     ~ as.character(compress(x, 0)),
            x >= 0.001 ~ paste0(compress(x, -3), "m"),
            x >= 1e-6  ~ paste0(compress(x, -6), "u")
        )
    }
    

提交回复
热议问题