R:在knitr :: kable

时间:2017-12-05 22:57:59

标签: r

我使用knitr :: kable

创建了下表
Week Cost   Disc    total
Wk1 10000   -4000   6000
Wk2 20000   -3000   17000
Wk3 30000   -2000   28000
Wk4 40000   -1000   39000

我想使用带有货币的会计格式显示数字。我知道你可以使用粘贴功能,但我想知道是否有更清洁的解决方案。以下是我希望它的外观:

Week Cost      Disc     total
Wk1 $10,000  ($4,000)  $6,000
Wk2 $20,000  ($3,000)  $17,000
Wk3 $30,000  ($2,000)  $28,000
Wk4 $40,000  ($1,000)  $39,000

有什么建议吗?

2 个答案:

答案 0 :(得分:5)

currency库中使用formattable

##Your sample df

df <- data.frame(Week = c("Wk1", "Wk2", "Wk3", "Wk4"), Cost = c(10000, 20000, 30000, 40000))


library(formattable)
df$Cost <- currency(df$Cost, digits = 0L)
df
#  Week    Cost
#1  Wk1 $10,000
#2  Wk2 $20,000
#3  Wk3 $30,000
#4  Wk4 $40,000

答案 1 :(得分:1)

我们可以使用 dollar 包的scales函数来编写一个名为format_dol_fun的辅助函数来执行此格式化:

format_dol_fun <- function(x){
  ifelse(x < 0, 
         paste0('(', scales::dollar(-x), ')'), 
         scales::dollar(x))
  }

dplyr::mutate_if(dat, is.numeric, format_dol_fun)

#   Week    Cost     Disc   total
# 1  Wk1 $10,000 ($4,000)  $6,000
# 2  Wk2 $20,000 ($3,000) $17,000
# 3  Wk3 $30,000 ($2,000) $28,000
# 4  Wk4 $40,000 ($1,000) $39,000

数据

dat <- structure(list(Week = c("Wk1", "Wk2", "Wk3", "Wk4"), 
                      Cost = c(10000L, 20000L, 30000L, 40000L), 
                      Disc = c(-4000L, -3000L, -2000L, -1000L), 
                      total = c(6000L, 17000L, 28000L, 39000L)), 
                 .Names = c("Week", "Cost", "Disc", "total"), 
                 class = "data.frame", 
                 row.names = c(NA, -4L))