在{gt}包中,我想对行组标题使用text\u transform(),以便呈现HTML,但我得到了"没有适用于"resolve\u location"的方法"错误.

在下面的示例中,您可以看到,如果locations参数为cells_body()(这不是我真正想要的),text\u transform()可以工作,但如果我想要的是cells_row_groups(),则text\u transform()不能工作.

思想?

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

推荐答案

经过反复试验和查看呈现的html代码后,我用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

R相关问答推荐

基于两个现有列创建新列

如何替换某个字符的所有出现,但如果该字符是字符串中的第一个,则不替换?

从R中的地址提取街道名称

在水平条形图中zoom x_轴

将模拟变量乘以多个观测结果中的模拟变量

使用R的序列覆盖

如何在ggplot 2线性图的每个方面显示每个组的误差条?

为什么st_join(ob1,ob2,left = True)返回具有比ob1更多功能的sf对象?

如何在xyplot中 for each 面板打印R^2

手动打印线型gplot

如何在modelsummary中重命名统计数据?

Rplotly中的Sankey Diagram:意外连接&

用关联字符串替换列名的元素

R spatstat Minkowski Sum()返回多个边界

无法定义沿边轨迹的 colored颜色 渐变(与值无关)

使用范围和单个数字将数字与字符串进行比较

Data.table';S GForce-将多个函数应用于多列(带可选参数)

减go R中列表的所有唯一元素对

我如何使用循环来编写冗余的Rmarkdown脚本?

有没有办法将不等长的列表转换为R中的数据帧