问题描述
我有很多数字,例如货币或美元:
I have large numbers, e.g. currency or dollar:
1 6,000,000
2 75,000,400
3 743,450,000
4 340,000
5 4,300,000
我想使用后缀来格式化它们,例如 M
(百万)和 B
(十亿):
I want to format them using suffixes, like M
(million) and B
(billion):
1 6.0 M
2 75.0 M
3 743.5 M
4 0.3 M
5 4.3 M
推荐答案
如果你从这个数字向量x
开始,
If you begin with this numeric vector x
,
x <- c(6e+06, 75000400, 743450000, 340000, 4300000)
您可以执行以下操作.
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"
如果您不关心尾随零,只需删除 format()
调用.
And if you're not concerned about trailing zeros, just remove the format()
call.
paste(round(x / 1e6, 1), "M")
# [1] "6 M" "75 M" "743.5 M" "0.3 M" "4.3 M"
或者,您可以使用 print 方法分配一个 S3 类,并将 y
保留为下面的数字.这里我使用 paste0()
使结果更清晰.
Alternatively, you could assign an S3 class with print method and keep y
as numeric underneath. Here I use paste0()
to make the result a bit more legible.
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
您也可以为数十亿和数万亿美元做同样的事情.有关如何将其放入数据框中的信息,请参阅 this answer,因为您需要 format()
和 as.data.frame()
方法.
You could do the same for billions and trillions as well. For information on how to put this into a data frame, see this answer, as you'll need both a format()
and an as.data.frame()
method.
这篇关于用百万 (M) 和十亿 (B) 后缀格式化数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!