gpt4 book ai didi

r - 跨单行格式化gt表的方法?

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

我正在尝试使用条件格式化我的 gt 表,但有点停滞不前。我发现的大多数示例都是基于列标题的格式。
这是示例表的代码,其中第一列名为“row”,值为 1-6。我如何让 gt 表仅向第 1 行的值 > 3.0 添加颜色?这是我的第一个问题,如果我搞砸了,请道歉!
Here's how I'd like the table to look like.

library(tidyverse)  
library(gt)

iris %>%
group_by(Species) %>%
slice_max(Sepal.Length, n=5) %>%
group_by(Species) %>%
mutate(row=row_number()) %>%
pivot_longer(-c(Species, row)) %>%
mutate(Species = str_to_title(Species),
name = gsub("\\.", " ", name)) %>%
pivot_wider(names_from=c(Species, name), values_from=value)%>%
gt() %>%
tab_spanner_delim(
delim="_"
)

最佳答案

我们可以添加 tab_stylecell_fill并指定 locationscolumnsrows

library(dplyr)
library(tidyr)
library(gt)
library(stringr)

iris %>%
group_by(Species) %>%
slice_max(Sepal.Length, n=5) %>%
group_by(Species) %>%
mutate(row=row_number()) %>%
pivot_longer(-c(Species, row)) %>%
mutate(Species = str_to_title(Species),
name = gsub("\\.", " ", name)) %>%
pivot_wider(names_from=c(Species, name), values_from=value)%>%
gt() %>%
tab_spanner_delim(
delim="_"
) %>%

tab_style(
style = list(
cell_fill(color = "lightgreen")

),
locations = cells_body(
columns = c(`Setosa_Sepal Length`, `Setosa_Sepal Width`,
`Versicolor_Sepal Length`, `Versicolor_Sepal Width`, `Versicolor_Petal Length`,
`Virginica_Sepal Length`,`Virginica_Sepal Width`, `Virginica_Petal Length`),

rows = 1
)
)
-输出
enter image description here

更新
根据评论,如果我们需要为每一列使用一个条件,那么我们可以使用 for循环遍历列名并添加条件层并更新原始 gt对象('tbl1')
tbl1 <- iris %>%   
group_by(Species) %>%
slice_max(Sepal.Length, n=5) %>%
group_by(Species) %>%
mutate(row=row_number()) %>%
pivot_longer(-c(Species, row)) %>%
mutate(Species = str_to_title(Species),
name = gsub("\\.", " ", name)) %>%
pivot_wider(names_from=c(Species, name), values_from=value)%>%
gt() %>%
tab_spanner_delim(
delim="_"
)

nm1 <- names(tbl1$`_data`)[-1]

for(i in seq_along(nm1)) {

tbl1 <- tbl1 %>%
tab_style(
style = list(
cell_fill(color = "lightgreen")

),
locations = cells_body(
columns = nm1[i],

rows = seq_along(tbl1$`_data`[[nm1[i]]]) == 1 &
tbl1$`_data`[[nm1[i]]] > 3
)
)
}
-输出
enter image description here

关于r - 跨单行格式化gt表的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68399449/

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