Programatically format column names with tidyr::last_col() and gt

Is this a bug or is gt not wired up to work with tidyr::last_col()?

library(gt)
library(tidyr)
## using tidyr::last_col()
dat <- data.frame(
  col1 = c(1, 1, 1),
  col2 = c(0, 1, 0),
  col3 = c(2, 0, 2)
)

gt(dat) %>%
  tab_style(
    style = cell_fill(color = "red"),
    locations = cells_body(
      columns = col1,
      rows = col1 < last_col()
    )
  )

image

## specifying the last column

gt(dat) %>%
  tab_style(
    style = cell_fill(color = "red"),
    locations = cells_body(
      columns = col1,
      rows = col1 < col3
    )
  )

image

gt converts the dat data.frame into an object that tidyr (using tidyselect in the background) is not equipped to handle, a gt_tbl

library(gt)

dat <- data.frame(
  col1 = c(1, 1, 1),
  col2 = c(0, 1, 0),
  col3 = c(2, 0, 2)
)

obj <- gt(dat)
class(obj)
#> [1] "gt_tbl" "list"

Take a look at str(obj) to see how different this is from a data.frame.

The most straightforward way of handling this is in {base}.

library(gt)

dat <- data.frame(
  col1 = c(1, 1, 1),
  col2 = c(0, 1, 0),
  col3 = c(2, 0, 2)
)

gt(dat) %>%
  tab_style(
    style = cell_fill(color = "red"),
    locations = cells_body(
      columns = col1,
      rows = which(dat[1] < dat[dim(dat)[2]]))
    )

[table output won't reprex cleanly but produces the desired result]

which returns the row numbers that satisfy some logical test. In this case, the test is whether dat[1] (dat$col1 works just as well) is strictly less than the last column. Getting the last column involves just a touch of sleight of hand: dim returns a vector of the number of rows and columns in a matrix-like object. The second number in the vector is the number of columns, in this case 3, so the right hand expression to < collapses to dat[3] and this sets rows to the vector 1,3.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.