英文:
How to color background of the same values in the whole table?
问题
我想要使用cell_spec
函数来获取result_tibble
中相同值的背景颜色。我的数据集如下:
name | F1 | F2 | F3 | F4 | F6 |
---|---|---|---|---|---|
name1 | 1 | 1 | 1 | 1 | 2 |
name2 | 1 | 2 | 2 | 2 | 2 |
因此,所有值为"1"的背景颜色将是一种颜色,所有值为"2"的背景颜色将是另一种颜色,依此类推(我的数据集中有6个不同的值1,2,3,4,5,6)。
我使用了以下代码,但不幸的是,它返回的仍然是相同的数据框,没有着色任何内容:
result_tibble %>% kbl() %>%
row_spec(1, bold = TRUE) %>%
cell_spec(1, background = "#FF0000") %>%
cell_spec(2, background = "#FFA500") %>%
cell_spec(3, background = "#FFFF00") %>%
cell_spec(4, background = "#00FF00") %>%
cell_spec(5, background = "#0000FF")
如果您能提供更多上下文或代码的信息,我将尽力帮助您找到问题所在。
英文:
I wanted to use cell_spec function to obtain colour at the background of the same values across tibble. My dataset looks like that:
name | F1 | F2 | F3 | F4 | F6 |
---|---|---|---|---|---|
name1 | 1 | 1 | 1 | 1 | 2 |
name2 | 1 | 2 | 2 | 2 | 2 |
So that background of all values with "1" will be one colour, background of all values with "2" will be second colour etc. (I have 6 values in dataset 1,2,3,4,5,6)
I used this code, but unfortunately it's returning the same dataframe, not colouring anything
result_tibble %>% kbl() %>% row_spec(1, bold = TRUE) %>% cell_spec(1, background = "#FF0000") %>% cell_spec(2, background = "#FFA500") %>% cell_spec(3, background = "#FFFF00") %>% cell_spec(4, background = "#00FF00") %>% cell_spec(5, background = "#0000FF")
答案1
得分: 1
我们可以在所需的列上使用 cell_spec()
函数,结合 case_when
来进行操作:
library(dplyr)
library(kableExtra)
df %>%
mutate(
across(F1:F6,
~ cell_spec(.x,
background = case_when(.x == 1 ~ "#FF0000",
.x == 2 ~ "#FFA500",
.x == 3 ~ "#FFFF00",
.x == 4 ~ "#00FF00",
.x == 5 ~ "#0000FF")
)
)
) %>%
kable(booktabs = TRUE, linesep = "", format = "html", escape = FALSE) %>%
kable_paper(full_width = FALSE)
英文:
We could use cell_spec()
function across the needed columns combined with a case_when:
library(dplyr)
library(kableExtra)
df %>%
mutate(
across(F1:F6,
~ cell_spec(.x,
background = case_when(.x == 1 ~ "#FF0000",
.x == 2 ~ "#FFA500",
.x == 3 ~ "#FFFF00",
.x == 4 ~ "#00FF00",
.x == 5 ~ "#0000FF")
)
)
) %>%
kable(booktabs = T, linesep = "", format = "html", escape = F) %>%
kable_paper(full_width = F)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论