gpt4 book ai didi

R: 条件高亮 kable

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

假设我有一个这样的矩阵:

set.seed(1234)
x = rnorm(10, mean=0, sd=1)
y = rnorm(10, mean=0, sd=1)
z = rnorm(10, mean=0, sd=1)
data=data.frame(rbind(x,y,z))

有什么方法可以在不指定列的情况下突出显示所有某些单元格(例如 >0 在这种情况下)?

我的预期结果会是这样(仅突出显示正值):

Example

在实际情况下,我有大约 30 列,如果我尝试对每一列进行 column_spec 逐一指定,我会感到筋疲力尽:

data %>%
column_spec(X1, color = "red") %>%
column_spec(X2, color = "red")

......

谢谢!

最佳答案

您可以执行以下操作

---
title: "Untitled"
output:
html_document: default
---

```{r warning=FALSE, message=FALSE, echo=FALSE}
set.seed(1234)
x = rnorm(10, mean=0, sd=1)
y = rnorm(10, mean=0, sd=1)
z = rnorm(10, mean=0, sd=1)
data=data.frame(rbind(x,y,z))

library(knitr)
library(kableExtra)
library(tidyverse)

data %>%
mutate_all(~cell_spec(.x, color = ifelse(.x < 0, "red"," black"))) %>%
kable(escape = F) %>%
kable_styling()
```

这会产生

enter image description here


更新

或者改变文字和背景颜色

---
title: "Untitled"
output:
html_document: default
---


```{r warning=FALSE, message=FALSE, echo=FALSE}
set.seed(1234)
x = rnorm(10, mean=0, sd=1)
y = rnorm(10, mean=0, sd=1)
z = rnorm(10, mean=0, sd=1)
data=data.frame(rbind(x,y,z))

library(knitr)
library(kableExtra)
library(tidyverse)

data %>%
mutate_all(~cell_spec(
.x,
color = ifelse(.x < 0, "white", "white"),
background = ifelse(.x < 0, "red"," black"))) %>%
kable(escape = F) %>%
kable_styling()
```

enter image description here

关于R: 条件高亮 kable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51509450/

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