无法在kableExtra中跨多个列应用cell_spec()

bvn4nwqk  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(116)

我尝试将cell_spec应用于data.frame中的多个列,但不断收到错误消息。我要突出显示所有小于1的值

df <- data.frame(vars =c("a","b","c","d","e","f","g","h"), d1 = c(0.5,1,5,7,9,3,4,1), d2 = c(0.6,3,5,4,7,9,4,2), d3 = c(4,2,5,7,9,2,2,3))

我可以像这样应用于单个细胞:

df[1,2] = cell_spec(df[1,2], background = "green")

enter image description here
但是单独突出显示所有单元格是很耗时的
我试过使用lapply

df[,2:4] <- lapply(df[,2:4], cell_spec(df[,2:4], background = ifelse(df[,2:4] < 2, "green", "white")))
df %>% kable(digits = 3, escape = FALSE, booktabs = TRUE) %>% kable_styling(bootstrap_options = "striped", latex_options="scale_down")

然后得到这个错误:
match.fun(FUN)错误:c(“'cell_spec(帕拉_p[,2:4],background = ifelse(para_p[,2:4] < '不是函数、字符或符号”,“'
2、“绿色”、“白色”)’不是函数、字符或符号”)
我试着写一个函数

df <- mutate_if(is.numeric, function(i){cell_spec(i, background = ifelse(i < .05, "green", "white"))}) %>%
  kable(digits = 3, escape = FALSE, booktabs = TRUE) %>% kable_styling(bootstrap_options = "striped", latex_options="scale_down")

但得到这个错误:
UseMethod(“tbl_vars”)出错:“tbl_vars”没有适用的方法应用于类“function”的对象
任何帮助将非常感谢!先谢谢你了

5f0d552i

5f0d552i1#

一种使用tidyverse的方法。使用mutateacross可以将函数应用于多个选定列。

library(kableExtra)
library(tidyverse)

df %>%
  mutate(across(d1:d3, ~cell_spec(.x, background = if_else(.x < 2, "green", "white")))) %>%
  kable(digits = 3, escape = FALSE, booktabs = TRUE) %>% 
  kable_styling(bootstrap_options = "striped", latex_options="scale_down")

table

相关问题