是否可以使用其他显示值(即用于确定color_bar大小的值以外的值)填充格式表color_bar
在下表中,我想使用以下ttl显示值覆盖这些值:
c(1000,1230,1239,1222,1300,1323,1221)
library(tidyverse)
library(knitr)
library(kableExtra)
library(formattable)
tchart <- data.frame(id = 1:7,
Student = c("Billy", "Jane", "Lawrence", "Thomas", "Clyde", "Elizabeth", "Billy Jean"),
grade3 = c(55,70,75,64,62,55,76),
ttl = c(105,120,125,114,112,105,126),
avg =c(52.31,53.0,54.2,51.9,52.0,52.7,53.0))
tchart %>%
mutate(id = cell_spec(id, "html", background = "red", color = "white", align = "center")) %>%
mutate(grade3 = color_bar("lightgreen")(grade3)) %>%
mutate(ttl = color_bar("lightgray")(ttl)) %>%
mutate(avg = color_tile("white","red")(avg)) %>%
kable("html", escape = F) %>%
kable_styling("hover", full_width = F) %>%
column_spec(4, width = "4cm")
我检查了文档,没有发现这种可能性,但是我希望有解决方法或自定义函数解决方案。
答案 0 :(得分:1)
我认为您不能完全传递另一组值,但是您可能会发现有两个可行的选择。
首先要注意的是color_bar()
可以接受两个值-一个颜色,以及一个将值的向量转换为0到1之间的数字的函数。默认情况下,该函数为{ {1}},将所有内容与最大值进行比较。但是,如果您将显示值用于formattable::proportion()
,则可以通过编写自己的函数将条形转换为所需的长度。 (请参阅:https://rdrr.io/cran/formattable/man/color_bar.html)
另一种可能性是制作自己的格式化程序。这里有一些例子: https://www.littlemissdata.com/blog/prettytables
因此,我认为您可以将所需的数字显示在显示屏上,并希望可以使用一个函数来转换或映射这些值,以获取所需的0到1之间的小节长度。
答案 1 :(得分:1)
添加新变量ttl_bar
以确定条形的大小,然后让变量ttl
显示该值。我使用gsub()
将ttl_bar
替换为ttl
。
tchart <- data.frame(id = 1:7,
Student = c("Billy", "Jane", "Lawrence", "Thomas", "Clyde", "Elizabeth", "Billy Jean"),
grade3 = c(55,70,75,64,62,55,76),
ttl = c(1000,1230,1239,1222,1300,1323,1221),
avg =c(52.31,53.0,54.2,51.9,52.0,52.7,53.0),
ttl_bar = c(105,120,125,114,112,105,126))
tchart %>%
mutate(id = cell_spec(id, "html", background = "red", color = "white", align = "center")) %>%
mutate(grade3 = color_bar("lightgreen")(grade3)) %>%
mutate(avg = color_tile("white","red")(avg)) %>%
mutate(ttl = pmap(list(ttl_bar, ttl, color_bar("lightgray")(ttl_bar)), gsub)) %>%
select(-ttl_bar) %>%
kable("html", escape = F) %>%
kable_styling("hover", full_width = F) %>%
column_spec(4, width = "4cm")
以一种更加谨慎的方式,将gsub()
改写为mutate(ttl = pmap(list(ttl_bar, ttl, color_bar("lightgray")(ttl_bar)), ~ gsub(paste0(">", ..1, "<"), paste0(">", ..2, "<"), ..3)))
。
我提出了一种更好的方法来使用color_bar()
中的函数,如下所示。
override = function(x, y) y / 200
tchart <- data.frame(id = 1:7,
Student = c("Billy", "Jane", "Lawrence", "Thomas", "Clyde", "Elizabeth", "Billy Jean"),
grade3 = c(55,70,75,64,62,55,76),
ttl = c(105,120,125,114,112,105,126),
avg =c(52.31,53.0,54.2,51.9,52.0,52.7,53.0),
ttl_bar = c(1000,1230,1239,1222,1300,1323,1221))
tchart %>%
mutate(id = cell_spec(id, "html", background = "red", color = "white", align = "center")) %>%
mutate(grade3 = color_bar("lightgreen")(grade3)) %>%
mutate(avg = color_tile("white","red")(avg)) %>%
mutate(ttl = color_bar("lightgray", fun = override, ttl)(ttl_bar)) %>%
select(-ttl_bar) %>%
kable("html", escape = F) %>%
kable_styling("hover", full_width = F) %>%
column_spec(4, width = "4cm")