Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading