Search code examples
rformattable

Style questions using formattable


I wish to display a dataframe in HTML using the R package formattable. In the table below, how do I add commas to the values, 6100 and 7500? Note I've rounded these values to the nearest hundred.

Also, how do I increase the size of the font and bold the entire Canada row?

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

Solution

  • You can add commas using formattable in different ways.

    One way is to add to columns as appropriate, using format and big.mark, for example:

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

    which would give you this:

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

    Then, to increase font size and bold a row, you can create a formatter and apply to that row:

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

    One other note is I added a space to row 1, col 1 instead of an empty string, as formattable didn't link that.

    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