我想以“会计”格式格式化我的负数,即用括号。 例如,我想将-1000000格式化为(1,000,000)。
我知道引入千位分隔符的方式:
prettyNum(-1000000, big.mark=",",scientific=F)
但是,我不知道如何引入括号。我希望能够将格式应用于整个向量,但我希望只有负数会受到影响。在引入千位分隔符之后,数字向量现在是 characater vector ,例如:
"-50,000" "50,000" "-50,000" "-49,979" "-48,778" "-45,279" "-41,321"
有什么想法吗?感谢。
答案 0 :(得分: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)"
答案 1 :(得分: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"
答案 2 :(得分:2)
您可以尝试使用内置函数accounting
的包formattable将会计格式应用于数字向量。
> # 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
答案 3 :(得分:1)
一种非常简单的方法是使用paste0
和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))
答案 4 :(得分:0)
也许这个?:
a <- prettyNum(-1000000, ,big.mark=",",scientific=F)
paste("(", sub("-", "", a), ")", sep = "")