我需要一个简单的函数或包格式:
1 6,000,000
2 75,000,400
3 743,450,000
4 340,000
5 4,300,000
Run Code Online (Sandbox Code Playgroud)
至:
1 6.0 M
2 75.0 M
3 743.5 M
4 0.3 M
5 4.3 M
Run Code Online (Sandbox Code Playgroud)
或者以更大的价值(数百万,数十亿)在表格中打印出来.
42-*_*42- 25
这用于findInterval定义后缀并确定分母.如果想要低于1.0或超过1万亿,可以轻松地向任一方向扩展:
comprss <- function(tx) {
div <- findInterval(as.numeric(gsub("\\,", "", tx)),
c(0, 1e3, 1e6, 1e9, 1e12) )
paste(round( as.numeric(gsub("\\,","",tx))/10^(3*(div-1)), 2),
c("","K","M","B","T")[div] )}
Run Code Online (Sandbox Code Playgroud)
如果输入是数字,则不需要删除as.numeric或gsub.这无疑是多余的,但会成功.这是Grgor的例子的结果:
> comprss (big_x)
[1] "123 " "500 " "999 " "1.05 K" "9 K"
[6] "49 K" "105.4 K" "998 K" "1.5 M" "20 M"
[11] "313.4 M" "453.12 B"
Run Code Online (Sandbox Code Playgroud)
并使用原始输入(实际上是一个因子变量.)
comprss (dat$V2)
[1] "6 M" "75 M" "743.45 M" "340 K" "4.3 M"
Run Code Online (Sandbox Code Playgroud)
当然,这些可以使用显式print命令和quotes = FALSE或使用而不使用引号打印cat.
Ric*_*ven 24
如果从这个数字向量开始x,
x <- c(6e+06, 75000400, 743450000, 340000, 4300000)
Run Code Online (Sandbox Code Playgroud)
你可以做到以下几点.
paste(format(round(x / 1e6, 1), trim = TRUE), "M")
# [1] "6.0 M" "75.0 M" "743.5 M" "0.3 M" "4.3 M"
Run Code Online (Sandbox Code Playgroud)
如果您不关心尾随零,只需删除该format()呼叫即可.
paste(round(x / 1e6, 1), "M")
# [1] "6 M" "75 M" "743.5 M" "0.3 M" "4.3 M"
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用print方法分配S3类,并y在下面保留为数字.在这里,我paste0()用来使结果更清晰.
print.million <- function(x, quote = FALSE, ...) {
x <- paste0(round(x / 1e6, 1), "M")
NextMethod(x, quote = quote, ...)
}
## assign the 'million' class to 'x'
class(x) <- "million"
x
# [1] 6M 75M 743.5M 0.3M 4.3M
x[]
# [1] 6000000 75000400 743450000 340000 4300000
Run Code Online (Sandbox Code Playgroud)
您也可以为数十亿甚至数万亿做同样的事情.有关如何将其放入数据框的信息,请参阅此答案,因为您需要a format()和as.data.frame()方法.
Seo*_*ter 12
该scales软件包的最新版本包括打印可读标签的功能。如果您使用的是 ggplot 或 tidyverse,scales则可能已经安装。不过,您可能需要更新软件包。
在这种情况下,label_number_si可以使用:
> library(scales)
> inp <- c(6000000, 75000400, 743450000, 340000, 4300000)
> label_number_si(accuracy=0.1)(inp)
[1] "6.0M" "75.0M" "743.4M" "340.0K" "4.3M"
Run Code Online (Sandbox Code Playgroud)
另一种选择,从数字(而不是字符)数字开始,适用于数百万和数十亿(及以下).您可以传递更多参数来自formatC定义输出,并在需要时扩展到Trillions.
m_b_format = function(x) {
b.index = x >= 1e9
m.index = x >= 1e5 & x < 1e9
output = formatC(x, format = "d", big.mark = ",")
output[b.index] = paste(formatC(x[b.index] / 1e9, digits = 1, format = "f"), "B")
output[m.index] = paste(formatC(x[m.index] / 1e6, digits = 1, format = "f"), "M")
return(output)
}
your_x = c(6e6, 75e6 + 400, 743450000, 340000, 43e6)
> m_b_format(your_x)
[1] "6.0 M" "75.0 M" "743.5 M" "0.3 M" "43.0 M"
big_x = c(123, 500, 999, 1050, 9000, 49000, 105400, 998000,
1.5e6, 2e7, 313402182, 453123634432)
> m_b_format(big_x)
[1] "123" "500" "999" "1,050" "9,000" "49,000"
[7] "0.1 M" "1.0 M" "1.5 M" "20.0 M" "313.4 M" "453.1 B"
Run Code Online (Sandbox Code Playgroud)