问题描述
我有很多,例如货币或美元:
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"
或者,您可以使用打印方法分配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
您甚至可以为数十亿亿万亿美元做同样的事情.有关如何将其放入数据框中的信息,请参见,因为您同时需要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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!