英文:
Highlight by row in gt
问题
我正在尝试查看是否可以按行高亮显示每行中的最大值。因此,使用以下数据集:
dat <- iris |>
dplyr::group_by(Species) |>
dplyr::summarise(
Sepal.Length = mean(Sepal.Length),
Sepal.Width = mean(Sepal.Width),
Petal.Length = mean(Petal.Length),
Petal.Width = mean(Petal.Width)
) |>
tidyr::pivot_longer(
cols = -Species,
names_to = "Measurement",
values_to = "Value"
) |>
tidyr::pivot_wider(
names_from = Species,
values_from = Value
)
dat
#> # A tibble: 4 × 4
#> Measurement setosa versicolor virginica
#> <chr> <dbl> <dbl> <dbl>
#> 1 Sepal.Length 5.01 5.94 6.59
#> 2 Sepal.Width 3.43 2.77 2.97
#> 3 Petal.Length 1.46 4.26 5.55
#> 4 Petal.Width 0.246 1.33 2.03
现在我知道可以按列进行高亮显示,如下所示:
gt(dat) |>
tab_style(
style = list(
cell_borders(
color = "#000000",
weight = px(2)
)
),
locations = cells_body(
columns = setosa,
rows = setosa == max(setosa)
)
)
这会生成如下图所示的结果:
但是是否有一种方法可以按行高亮显示最大值?基本上在这里,我想要在具有最大测量值的物种周围绘制一个框。
英文:
I am trying to see if gt can highlight by rows the max value in that row. So take this dataset:
dat <- iris |>
dplyr::group_by(Species) |>
dplyr::summarise(
Sepal.Length = mean(Sepal.Length),
Sepal.Width = mean(Sepal.Width),
Petal.Length = mean(Petal.Length),
Petal.Width = mean(Petal.Width)
) |>
tidyr::pivot_longer(
cols = -Species,
names_to = "Measurement",
values_to = "Value"
) |>
tidyr::pivot_wider(
names_from = Species,
values_from = Value
)
dat
#> # A tibble: 4 × 4
#> Measurement setosa versicolor virginica
#> <chr> <dbl> <dbl> <dbl>
#> 1 Sepal.Length 5.01 5.94 6.59
#> 2 Sepal.Width 3.43 2.77 2.97
#> 3 Petal.Length 1.46 4.26 5.55
#> 4 Petal.Width 0.246 1.33 2.03
Now I know I can highlight by column like this:
gt(dat) |>
tab_style(
style = list(
cell_borders(
color = "#000000",
weight = px(2)
)
),
locations = cells_body(
columns = setosa,
rows = setosa == max(setosa)
)
)
which produces:
But if there any way to highlight the max by row? Basically here I want a box drawn around which species has the max of the measurements.
答案1
得分: 2
你可以使用一个 cells_body
列表:
gt(dat) |>
tab_style(style = list(cell_borders(color = "#000000",
weight = px(2))),
locations = lapply(
1:nrow(dat),
FUN =
function(rowNumber) {
cells_body(columns = which.max(dat[rowNumber, ]),
rows = rowNumber)
}
))
英文:
You can use a list of cells_body
:
gt(dat) |>
tab_style(style = list(cell_borders(color = "#000000",
weight = px(2))),
locations = lapply(
1:nrow(dat),
FUN =
function(rowNumber) {
cells_body(columns = which.max(dat[rowNumber, ]),
rows = rowNumber)
}
))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论