我是這個gt包的新手。我有一組資料,如t(mtcars)). 例如
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
如何根據每行的數字設定顏色?我只知道在相反的情況下該怎么做。例如
data_color(columns = vars("mpg"),
colors = scales::col_numeric(c("red","green"),
domain = c(0,30)))
或者如果我用mtcars? 任何幫助表示贊賞。謝謝!
uj5u.com熱心網友回復:
這是一個小例子:(新管道的 R >= 4.1)
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
給出:

uj5u.com熱心網友回復:
我想這就是你想要的,但我可能會離開。
此解決方案的缺點是您需要根據rows引數的資料集更改索引,并且您需要知道要在表中添加顏色的變數的行索引。
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"))
)
這會給你:

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/340859.html
上一篇:獲取陣列中當前索引前后的5項
下一篇:基于日期的總和值
