gpt4 book ai didi

r - gt表中多列的条件格式

转载 作者:行者123 更新时间:2023-12-04 04:12:46 24 4
gpt4 key购买 nike

这是我的第一篇文章,所以如果我搞砸了,请道歉。我正在尝试将条件格式应用于 gt 表的多列(比较样本 SampA、SampB 和 SampB 的结果以限制)。跟随其中一位gt examples的领头羊和一个不同的 stack overflow Q ,我设法使用以下代码将其应用于单个列(变量):

## Conditional Formatting of single column in gt table

samples = as_tibble(cbind("Chem"=c("Cd","Pb","Zn"),
"Limit"=c("0.005","0.05","0.007"),
"SampA" = c("0.001","0.15","0.003"),
"SampB" = c("0.002","0.04","0.005"),
"SampC" = c("0.009","0.23","0.03")))

gt(samples,rowname_col="Chem") %>% tab_style(
style = list(
cell_fill(color = "grey80"),
cell_text(weight = "bold")
),
locations = cells_body(
columns = vars(SampA),
rows = SampA >= Limit
)
) %>% tab_spanner(
label = "Samples",
columns = vars(SampA,SampB,SampC))

Successful conditional formatting for single column

但是,我没有成功尝试将其扩展到多个列。我可以得到 'columns' 参数来处理 'vars(SampA,SampB,SampC)'。将 'rows' 参数保留为 'SampA >= Limit',格式“有效”,因为 SampA >= Limit 的所有行都在三个 Samp 列中突出显示,但这不是我想要的。运行下面的代码最终没有任何列的格式。
        locations = cells_body(
columns = vars(SampA,SampB,SampC),
rows = vars(SampA,SampB,SampC) >= Limit
)

Unsuccessful multiple column conditional formatting

通过重复为每一列量身定制的“style_tab()”,我已经能够“蛮力”我所追求的,但我知道必须有更好的方法来实现我的目标。帮助?

gt conditional formatting success by brute force.

最佳答案


library(gt)
samples = as_tibble(cbind("Chem"=c("Cd","Pb","Zn"),
"Limit"=c("0.005","0.05","0.007"),
"SampA" = c("0.001","0.15","0.003"),
"SampB" = c("0.002","0.04","0.005"),
"SampC" = c("0.009","0.23","0.03")))

samples <- samples %>%
mutate(Limit = as.numeric(Limit))

gt(samples,
rowname_col="Chem") %>%
tab_style(style = list(cell_fill(color = 'yellow'),
cell_text(weight = 'bold')),
locations = cells_body(columns=vars(SampA),
rows = SampA >= Limit)) %>%
tab_style(style = list(cell_fill(color = 'yellow'),
cell_text(weight = 'bold')),
locations = cells_body(columns=vars(SampB),
rows = SampB >= Limit)) %>%
tab_style(style = list(cell_fill(color = 'yellow'),
cell_text(weight = 'bold')),
locations = cells_body(columns=vars(SampC),
rows = SampC >= Limit)) %>%
tab_spanner(
label = "Samples",
columns = vars(SampA,SampB,SampC))
Sample

关于r - gt表中多列的条件格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61435048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com