在控制台中用逗号显示数字

问题描述 投票:1回答:1

我正在处理一大堆数字。我知道如何将数字转换为逗号格式:Comma separator for numbers in R?。我不知道该怎么做是在控制台中用逗号显示数字而不用从数字转换类。我希望能够看到逗号,以便我可以在工作时比较数字 - 但需要将数字保持为数字以进行计算。我知道你可以摆脱科学记数:How to disable scientific notation? - 但找不到逗号或美元格式的等价物。

r
1个回答
5
投票

您可以为print()创建一个新方法,对于我称之为“bignum”的自定义类:

print.bignum <- function(x) {
    print(format(x, scientific = FALSE, big.mark = ",", trim = TRUE))
}

x <- c(1e6, 2e4, 5e8)
class(x) <- c(class(x), "bignum")

x

[1] "1,000,000"   "20,000"      "500,000,000"

x * 2

[1] "2,000,000"     "40,000"        "1,000,000,000"

y <- x + 1
y

[1] "1,000,001"   "20,001"      "500,000,001"


class(y) <- "numeric"
y

[1]   1000001     20001 500000001

对于任何数字对象x,如果通过class(x) <- c(class(x), "bignum")将“bignum”添加到类属性,它将始终打印您所描述的如何打印,但应该表现为数字,否则,如上所示。

© www.soinside.com 2019 - 2024. All rights reserved.