我尝试将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”的对象
任何帮助将非常感谢!先谢谢你了
1条答案
按热度按时间5f0d552i1#
一种使用
tidyverse
的方法。使用mutate
和across
可以将函数应用于多个选定列。table