This question is related to this one:
My question: How can I modify my code to apply these condition to all columns!
e.g all 0
are red and all 4
are blue!
CodePudding user response:
If we want only to do this on particular columns, create a vector of names ('nm1') and loop over only those columns, within the loop, get the index that meets the condition in rows
library(dplyr)
library(gt)
tbl1 <- mtcars %>%
gt()
nm1 <- c("cyl", "vs", "am", "gear", "carb")
for(i in seq_along(nm1)) {
tbl1 <- tbl1 %>%
tab_style(
style = list(
cell_text(color = "red", weight = "bold")
),
locations = cells_body(
columns = nm1[i],
rows = tbl1$`_data`[[nm1[i]]] == 0
)
) %>%
tab_style(
style = list(
cell_text(color = "blue", weight = "bold")
),
locations = cells_body(
columns = nm1[i],
rows = tbl1$`_data`[[nm1[i]]] == 4
)
)
}
-output
Another option would be to create the gt
object in each column using across
, store as_raw_html
and then call the gt
on top of the output with fmt_markdown
out <- mtcars %>%
summarise(across(everything(), ~
setNames(tibble(.x), cur_column()) %>%
gt() %>%
tab_style(
style = cell_text(color = "red", weight = "bold"),
locations = cells_body(
columns = cur_column(),
rows = .x == 0
)
) %>%
tab_style(
style = cell_text(color = "blue", weight = "bold"),
locations = cells_body(
columns = cur_column(),
rows = .x == 4
)
) %>%
as_raw_html()
))
out1 <- out %>%
gt() %>%
fmt_markdown(columns = everything())
out1