I am new to the gt
package. I have a set of data like t(mtcars))
. For example
Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout Valiant Duster 360 Merc 240D Merc 230 Merc 280
mpg 21.00 21.000 22.80 21.400 18.70 18.10 14.30 24.40 22.80 19.20
cyl 6.00 6.000 4.00 6.000 8.00 6.00 8.00 4.00 4.00 6.00
disp 160.00 160.000 108.00 258.000 360.00 225.00 360.00 146.70 140.80 167.60
hp 110.00 110.000 93.00 110.000 175.00 105.00 245.00 62.00 95.00 123.00
drat 3.90 3.900 3.85 3.080 3.15 2.76 3.21 3.69 3.92 3.92
wt 2.62 2.875 2.32 3.215 3.44 3.46 3.57 3.19 3.15 3.44
How to set colors based on the numbers on each row? I only know how to do it when it is the other way around. For example
data_color(columns = vars("mpg"),
colors = scales::col_numeric(c("red","green"),
domain = c(0,30)))
Or any way to transpose at the end if I make the table with data in the form of mtcars
? Any help is appreciated. Thanks!
CodePudding user response:
Here's a little example: (R >= 4.1 for new pipe)
library(gt)
df <- t(mtcars) |> as.data.frame() |> subset(select = 1:5)
gt_tbl <- df |> gt() |>
tab_style(
locations = cells_body(
columns = `Datsun 710`,
rows = `Datsun 710` > 30
),
style = list(cell_text(color = 'red'))
)
gt_tbl
CodePudding user response:
I think this is what you want, but I might be off.
The disadvantage for this solution is that you need to change the indices depending on your dataset for the rows
argument, and you'll need to know the row index of the variable that you want to add color to in the table.
head(as_tibble(t(mtcars))) %>%
gt() %>%
data_color(
columns = where(is.numeric),
colors = scales::col_numeric(
palette = c("red", "green"),
domain = c(0,30)
)
) %>%
tab_style(
location = cells_body(
columns = where(is.numeric),
rows = 2:6
),
style = list(cell_text(color = "black"),
cell_fill(color = "white"))
)
This will give you: