【问题标题】:R Markdown - How can I give rows different formats?R Markdown - 我怎样才能给行不同的格式?
【发布时间】:2020-05-19 22:51:18
【问题描述】:

我目前正在使用具有许多数值的数据框,有些是百分比,有些是美元值,有些只是标量值。我可以用适当的格式格式化(使用formattable 包)列,但我希望能够对 rows 做同样的事情。

您知道如何实现吗?特别是,这是用于 LaTeX/PDF 输出

可重现的例子:

structure(list(seg1 = c(117.67, 117.68, -69.14, 0.0100000000000051, 
-186.81, 0, 0.4, 0, 79, 168.18, 387.95, 67.272), seg2 = c(174.29, 
212.75, 212.76, 38.46, 38.47, 0, 0, 0.35, 79, 168.18, 387.95, 
135.7825), seg3 = c(458.08, 516.15, 352.38, 58.07, -105.7, 0, 
0.25, 0, 79, 168.18, 387.95, 42.045)), class = "data.frame", row.names = c("Reference utility to customer", 
"HP_PPM30 utility to customer", "HP_wireless utility to customer", 
"Pricing room product 1", "Pricing room product 2", "Reference bought", 
"Product 1 bought", "Product 2 bought", "Reference mg contr.", 
"Product 1 mg contr.", "Product 2 mg contr.", "Profits per segment"
))

产量

                                    seg1     seg2     seg3
Reference utility to customer    117.670 174.2900  458.080
HP_PPM30 utility to customer     117.680 212.7500  516.150
HP_wireless utility to customer  -69.140 212.7600  352.380
Pricing room product 1             0.010  38.4600   58.070
Pricing room product 2          -186.810  38.4700 -105.700
Reference bought                   0.000   0.0000    0.000
Product 1 bought                   0.400   0.0000    0.250
Product 2 bought                   0.000   0.3500    0.000
Reference mg contr.               79.000  79.0000   79.000
Product 1 mg contr.              168.180 168.1800  168.180
Product 2 mg contr.              387.950 387.9500  387.950
Profits per segment               67.272 135.7825   42.045

是否有可能获得显示“mg contr.”的 ROWS。显示货币格式,以及显示“购买”百分比格式的行?我可以使用%>% currency() 做列,但不知道行。当然,这必须在 R-markdown/latex 级别实现。

为了更清楚起见,这在 LaTeX 中是可行的,或者仅使用普通的内联 R 和 markdown 表,但如果以编程方式实现这一点,那就太棒了。

【问题讨论】:

  • gt.rstudio.com 是一个想法
  • SebastianRivas,我认为如果您提供一些可重复的数据(dput(head(x))data.frame(...))以及您的预期输出,这将是有益的。谢谢!

标签: r r-markdown


【解决方案1】:

您可以使用dplyrcase_when 创建一列新的字符串 值,每个值都根据某种规则进行格式化。您可以使用scales 进行格式化。例如

output %>%
  mutate(new_value = case_when(
    variable %in% c("income", "taxable income") ~ scales::dollar(old_value),
    variable %in% c("loss (pct)", "tax rate") ~ scales::percent(old_value)
  )

【讨论】:

  • 不是每列的格式不同,而不是每一行?
  • 不,不会
猜你喜欢
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
  • 2022-09-28
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
相关资源
最近更新 更多