rformattable

Referring to a formattable table's column number instead of variable name


I have a data frame where it's a column of yearly numbers. In an effort to be more efficient and not have to change the numbers every year, I'm trying to reduce the things I'll have to edit every year.

Sample data frame:

bach_STEM_wide <- data.frame(
  Name = c("Technology", "Science", "Engineering"),
  "Pct. Diff. from 2013 to 2023" = c(-5.2, 7.3, -1.8),
  "Pct. Diff. from 2022 to 2023" = c(2.1, -3.5, 1.2))

I want to apply these formatting rules to the table but I want to refer to "Pct. Diff. from 2013 to 2023" by its column number not "Pct. Diff. from 2013 to 2023"

I tried:

column_number <- 2

# Refer to the column by its column number
column_data <- bach_STEM_wide[[column_number]]

formattable(bach_STEM_wide, align = "l", list(
  Name=formatter(
    "span",
    style = x ~ ifelse(x == "Technology", 
                       style(font.weight = "bold"), NA)),
  column_data  = formatter(
    "span",
    style = x ~ style(color = ifelse(x < 0 , "orange", "blue")),
    x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)), 
  one_year_pct_diff_header = formatter(
    "span",
    style = x ~ style(color = ifelse(x < 0 , "orange", "blue")),
    x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)))
)

and it didn't work.


Solution

  • formattable::area() can be used to target cells by index.

    library(formattable)
    
    column_number <- 2
    
    formattable(bach_STEM_wide, align = "l", list(
      Name=formatter(
        "span",
        style = x ~ ifelse(x == "Technology", 
                           style(font.weight = "bold"), NA)),
      area(TRUE, column_number) ~ formatter(
        "span",
        style = x ~ style(color = ifelse(x < 0 , "orange", "blue")),
        x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)), 
      one_year_pct_diff_header = formatter(
        "span",
        style = x ~ style(color = ifelse(x < 0 , "orange", "blue")),
        x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)))
    )
    

    enter image description here