使用formattable样式化问题

时间:2019-10-13 02:21:35

标签: r formattable

我希望使用R包格式表以HTML显示数据框。在下表中,如何将逗号添加到值6100和7500?请注意,我已经将这些值四舍五入到最接近的百位。

此外,如何增加字体大小并加粗整个加拿大行?

library(tidyverse)
library(formattable)

target_year = 1980
current_year = 2019

can_target = 20
can2019 = 37

world_target = 6123
world2019 = 7456

can_change <- (can2019 - can_target) / can_target
world_change <- (world2019 - world_target) / world_target

can_world_table <- tibble(
  region = c("Canada", "World"),
  ty = c(can_target, round(world_target, digits = -2)),
  cy = c(can2019, round(world2019, digits = -2)),
  change = percent(c(can_change, world_change), 0)
) %>% 
  set_names(c("", target_year, current_year, "Change"))


can_world_table

2 个答案:

答案 0 :(得分:1)

您可以使用formattable以不同的方式添加逗号。

一种方法是使用formatbig.mark适当地添加到列,例如:

ty = c(can_target, format(round(world_target, digits = -2), big.mark = ",")),
cy = c(can2019, format(round(world2019, digits = -2), big.mark = ",")),

这将为您提供:

# A tibble: 2 x 4
  ` `    `1980` `2019` Change    
  <chr>  <chr>  <chr>  <formttbl>
1 Canada 20     37     85%       
2 World  6,100  7,500  22%

然后,要增加字体大小并加粗一行,可以创建一个格式化程序并将其应用于该行:

lg_bold <- formatter("span", style = ~style("font.weight" = "bold", "font.size" = "16px"))
formattable(can_world_table, list(area(row = 2) ~ lg_bold))

另一个要注意的是,我在第1行第1行中添加了一个空格,而不是一个空字符串,因为formattable并未链接该空格。

can_world_table <- tibble(
  region = c("Canada", "World"),
  ty = c(can_target, format(round(world_target, digits = -2), big.mark = ",")),
  cy = c(can2019, format(round(world2019, digits = -2), big.mark = ",")),
  change = percent(c(can_change, world_change), 0)
) %>% 
  set_names(c(" ", target_year, current_year, "Change")) # Added space for formattable

lg_bold <- formatter("span", style = ~style("font.weight" = "bold", "font.size" = "16px"))
formattable(can_world_table, list(area(row = 2) ~ lg_bold))

formattable table

答案 1 :(得分:0)

我可以回答您问题的“在值中添加逗号”部分。

我过去使用过的一个特定库数字格式

最终结果是字符类型,因此如果您打算显示该值,则很有用,但如果您打算在计算中使用它,则无用。

> library('numform')
> v <- f_comma(c(100000,1000))
> v
[1] "100,000" "1,000"

Doco在这里:https://cran.r-project.org/web/packages/numform/numform.pdf