3

我想将我的负数格式化为“会计”格式,即带括号。例如,我想将 -1000000 格式化为 (1,000,000)。

我知道引入千位分隔符的方式:

 prettyNum(-1000000, big.mark=",",scientific=F)

但是,我不确定如何引入括号。我希望能够将格式应用于整个向量,但我希望只影响负数。并不是说在引入千位分隔符之后,数字向量现在是一个字符向量,例如:

 "-50,000" "50,000"  "-50,000" "-49,979" "-48,778" "-45,279" "-41,321"

有任何想法吗?谢谢。

4

5 回答 5

3

另一种方式,没有正则表达式:

x <- c(-50000, 50000, -50000, -49979, -48778, -45279, -41321)
x.comma <- prettyNum(abs(x), big.mark=',')
ifelse(x >= 0, x.comma, paste0('(', x.comma, ')'))
# [1] "(50,000)" "50,000"   "(50,000)" "(49,979)" "(48,778)" "(45,279)" "(41,321)"
于 2013-10-25T14:17:25.767 回答
3

您可以尝试我的包formattableaccounting ,它具有将会计格式应用于数字向量的内置功能。

> # devtools::install_github("renkun-ken/formattable")
> library(formattable)
> accounting(c(123456,-23456,-789123456))
[1] 123,456.00       (23,456.00)      (789,123,456.00)

您可以将数字打印为整数:

> accounting(c(123456,-23456,-789123456), format = "d")
[1] 123,456       (23,456)      (789,123,456)

这些数字适用于算术计算:

> money <- accounting(c(123456,-23456,-789123456), format = "d")
> money
[1] 123,456       (23,456)      (789,123,456)
> money + 5000
[1] 128,456       (18,456)      (789,118,456)

它也适用于data.frame打印:

> data.frame(date = as.Date("2015-01-01") + 1:10, 
    balance = accounting(cumsum(rnorm(10, 0, 100000))))
         date      balance
1  2015-01-02  (21,929.80)
2  2015-01-03 (246,927.59)
3  2015-01-04 (156,210.85)
4  2015-01-05 (135,122.80)
5  2015-01-06 (199,713.06)
6  2015-01-07  (91,938.03)
7  2015-01-08  (34,600.47)
8  2015-01-09   147,165.57
9  2015-01-10   180,443.31
10 2015-01-11   251,141.04
于 2015-05-30T13:08:36.780 回答
2

这是一种提供前导空格的方法:

x <- c(-10000000, -4444, 1, 333)

num <- gsub("^\\s+|\\s+$", "", prettyNum(abs(x), ,big.mark=",", scientific=F))
num[x < 0] <- sprintf("(%s)", num[x < 0])
sprintf(paste0("%0", max(nchar(as.character(num))), "s"), num)


## [1] "(10,000,000)" "     (4,444)" "           1" "         333"
于 2013-10-25T14:11:47.793 回答
1

一个非常简单的方法是使用paste0and sub。这是一个简单的函数:

my.format <- function(num){
  ind <- grepl("-", num)
  num[ind] <-  paste0("(", sub("-", "", num[ind]), ")")
  num
}

> num <- c("-50,000", "50,000",  "-50,000", "-49,979", "-48,778", "-45,279", "-41,321")
> my.format(num)
[1] "(50,000)" "50,000"   "(50,000)" "(49,979)" "(48,778)" "(45,279)" "(41,321)"

如果你想扭转这种情况,假设你有一个这样的向量:

num2 <- my.format(num)

并且您想替换(·)-,然后尝试

sub(")", "", sub("\\(", "-", num2))
于 2013-10-25T13:59:16.950 回答
0

也许这个?:

a <- prettyNum(-1000000, ,big.mark=",",scientific=F)
paste("(", sub("-", "", a), ")", sep = "")
于 2013-10-25T14:01:06.367 回答