I have a gt table in R and want to color all of the values in the same color. For example, using the mtcars dataset, how could I color all values of 0 in red and all values of 4 in blue?
library("gt")
mtcars %>%
gt()
I tried to use tab_style()
and data_color()
with no success so far. To be clear, I want an easy solution that will work with tables that have dozens of columns, without having to add myriads of additional tab_style()
and data_color()
or other additional arguments, if that's possible.
CodePudding user response:
We could use a for
loop
library(dplyr)
library(gt)
tbl1 <- mtcars %>%
gt()
nm1 <- names(mtcars)
for(i in seq_along(nm1)) {
tbl1 <- tbl1 %>%
tab_style(
style = list(
cell_fill(color = "red")
),
locations = cells_body(
columns = nm1[i],
rows = tbl1$`_data`[[nm1[i]]] == 0
)
) %>%
tab_style(
style = list(
cell_fill(color = "blue")
),
locations = cells_body(
columns = nm1[i],
rows = tbl1$`_data`[[nm1[i]]] == 4
)
)
}
-output
CodePudding user response:
If we want to change the font colors only then we could use cell_text
and make use of @akrun's loop solution, see also here