英文:
Styling cells in a gt table based on detection of a string in their contents
问题
我正在使用R中的gt()包,尝试根据单元格内容对它们进行样式设置,但遇到了一些困难。
这是一个最小的示例。
让我们从一个tibble my_data
开始:
my_data <- tibble(person = c('pablo','spots','harry'),
outcome_1 = c('good','bad','good'),
outcome_2 = c('good','good','bad'))
现在让我们尝试呈现一个gt表格,并对包含文本'bad'的单元格进行颜色设置,使它们变成红色。
my_data %>%
gt() %>%
tab_style(
style = list(
cell_fill(color = 'red'),
cell_text(weight = 'bold')),
locations = cells_body(
columns = starts_with('outcome_'),
rows = contains('bad')
)
)
但是它不起作用!包含单词'bad'的单元格应该具有粗体字重和红色背景。相反,我得到了...
文档中的locations
示例似乎非常简单。我正在遵循cells_body
的用法,根据我能看到的正确应用了starts_with
和contains
的选择助手。
那么问题是什么?我认为我在这里有一个基本的误解!
英文:
I am using the gt() package in R and am having a rough time trying to style my cells based on their content.
Here's a minimal example.
Let's start with a tibble, my_data
:
my_data <- tibble(person = c('pablo','spots','harry'),
outcome_1 = c('good','bad','good'),
outcome_2 = c('good','good','bad'))
Let's now try to render a gt table and color the cells that contain the text 'bad' so that they're red.
my_data |>
gt() |>
tab_style(
style = list(
cell_fill(color = 'red'),
cell_text(weight = 'bold')),
locations = cells_body(
columns = starts_with('outcome_'),
rows = contains('bad')
)
)
But it doesn't work! The cells containing the word 'bad' should have bold font weight and should have a red background. Instead I get...
The example in the docs for locations
seems fairly straightforward. I am following what it says in for cells_body
usage and as far as I can tell correctly applying the selection helpers starts_with
and contains
.
So what's the problem? I think I got a fundamental misunderstanding here of how this is supposed to work!
答案1
得分: 3
以下是您要翻译的代码部分:
sort of hackish but doing its job:
my_data |>
gt() |>
tab_style(
style = list(
cell_fill(color = 'red'),
cell_text(weight = 'bold')),
locations = names(my_data)[grep('outcome', names(my_data))] |>
lapply(FUN = (col_name){
cells_body(columns = col_name,
rows = grepl('bad', my_data[[col_name]])
)
})
)
)
It works because you can supply a *list* of `cells_body` selections, which is what `lapply` produces (here as an inline call).
<details>
<summary>英文:</summary>
sort of hackish but doing its job:
my_data |>
gt() |>
tab_style(
style = list(
cell_fill(color = 'red'),
cell_text(weight = 'bold')),
locations = names(my_data)[grep('outcome', names(my_data))] |>
lapply(FUN = (col_name){
cells_body(columns = col_name,
rows = grepl('bad', my_data[[col_name]])
)
})
)
)
It works because you can supply a *list* of `cells_body` selections, which is what `lapply` produces (here as an inline call).
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论