Home > front end >  Applying text_transform() to row groups in R gt
Applying text_transform() to row groups in R gt

Time:06-23

In the {gt} package I want to use text_transform() on the row group titles in order to render the HTML but I'm getting the `no applicable method for 'resolve_location' error.

In my example below, you can see that text_transform() works if the locations argument is cells_body() (which is not what I actually want) but not if it's cells_row_groups() which is what I want.

Thoughts?

Zev

# As an experiment, I put HTML in both a value and in the groups, though
# in the real data there is only HTML in groups.

tbl <- tibble(values = c("test<sup>2</sup>", 2:4), groups = c("x<sup>2</sup>", "x<sup>2</sup>", "y", "y"))

unescape_html <- function(str){
  xml2::xml_text(xml2::read_html(paste0("<x>", str, "</x>")))
}

# Error, no applicable method for resolve_location
tbl |> 
  gt::gt(groupname_col = "b") |> 
  gt::text_transform(
    locations = gt::cells_row_groups(),
    fn = function(x){
      x <- purrr::map_chr(x, unescape_html)
      paste("<span style=color:red;>", x, "</span>")
    }
  )


# This works so it shows that I'm close :)
tbl |> 
  gt::gt(groupname_col = "b") |> 
  gt::text_transform(
    locations = gt::cells_body(columns = 1),
    fn = function(x){
      x <- purrr::map_chr(x, unescape_html)
      paste("<span style=color:red;>", x, "</span>")
    }
  )

enter image description here

CodePudding user response:

After some trial and error and a look at the rendered html code I figured out a solution using gt::html:

tbl <- tibble::tibble(values = c("test<sup>2</sup>", 2:4), groups = c("x<sup>2</sup>", "x<sup>2</sup>", "y", "y"))

unescape_html <- function(str){
  xml2::xml_text(xml2::read_html(paste0("<x>", str, "</x>")))
}

tbl |> 
  gt::gt(groupname_col = "groups") |> 
  gt::text_transform(
    locations = gt::cells_row_groups(),
    fn = function(x) {
      purrr::map(x, ~ gt::html(paste("<span style=color:blue;>", .x, "</span>")))
    }
  ) |> 
  gt::text_transform(
    locations = gt::cells_body(columns = 1),
    fn = function(x){
      x <- purrr::map_chr(x, unescape_html)
      paste("<span style=color:red;>", x, "</span>")
    }
  )

enter image description here

  •  Tags:  
  • r gt
  • Related