Search code examples
rtidyversegt

In gt: Selecting cells to format based on relative positions of cells and columns, not a literal column name


In the example below, table 1 is a working example that specifies the column name directly in the row specification. This gives the result I want, but I don't wish to call the column names directly. Instead I want to refer to them indirectly (because I was be using this code on many tables of the same dimensions but with different names. table2 attempts this, but does not work. Is there a proper way to achieve my goal?

df <- data.frame(colA = c(5, 10), colB = c(8, 9))
table1 <- df %>%
  gt() %>%
  tab_style(style = cell_text(color = "red"),
            locations = cells_body(columns = colB,
                                   rows = colB >8))
table1


table2 <- df %>%
  gt() %>%
  tab_style(style = cell_text(color = "red"),
            locations = cells_body(columns = ends_with("B"),
                                   rows = last_col() >8))
table2

Solution

  • You need to provide a full select statement:

    my_col <- names(df %>% select(ends_with("B")))
    
    table2 <- df %>%
      gt() %>%
      tab_style(
        style = cell_text(color = "red"),
        locations = cells_body(
          columns = all_of(my_col),
          rows = !!sym(my_col) > 8))
    table2