r - 如何使用 R 中的“huxtable”库为表格中所需的单元格着色。哪种方式更优雅?
问题描述
我需要用灰色标记表格中的一些特殊单元格。像这样的东西:
```{r}
library(huxtable)
library(magrittr)
sample_df <- data.frame(matrix(1:25, nrow = 5))
sample_df %>% as_huxtable() %>% set_all_borders(1) %>%
set_background_color(row = 2, col = 1, value = "grey") %>%
set_background_color(row = 3, col = 2, value = "grey") %>%
set_background_color(row = 4, col = 3, value = "grey") %>%
set_background_color(row = 5, col = 4, value = "grey") %>%
set_background_color(row = 6, col = 5, value = "grey")
```
在“knitr”作为 HTML 文档之后,它给了我以下内容(作为屏幕截图):
这就是我需要得到的。但是,我的问题是:有什么比编写这样的代码字符串更优雅的方法呢?我试着这样做:
my_fan <- function(.data) {for (i in c(2:6))
{set_background_color(.data, row = i, col = i-1, value = "grey")}
.data
}
sample_df %>%
as_huxtable() %>% set_all_borders %>%
my_fan()
...而且它根本没有给我任何结果。有任何想法吗?
解决方案
您可以使用老式界面和关于 R 子集的鲜为人知的事实:
sample_df <- data.frame(matrix(1:25, nrow = 5))
sample_df <- as_huxtable(sample_df)
background_color(sample_df)[matrix(c(2:6, 1:5), ncol = 2)] <- "grey"
sample_df
来自?Extract
:
当通过 [ 索引数组时,单个参数 i 可以是具有与 x 维数一样多的列的矩阵;结果是一个向量,其元素对应于 i 的每一行中的索引集。
或者,如果你想变得很酷:
diag(background_color(sample_df[-1,])) <- "grey"
我很惊讶这有效:-)
推荐阅读
- javascript - 从另一个人那里解决一个外部承诺——交替执行顺序?
- excel - 使用 VBA 自动填充(导入新导出时扩展公式)
- kotlin - Kotlin - 检查对象是否实现特定接口
- django - 如何过滤一组值的字段
- swift - libsybdb.a(dblib.o)' 不包含位码
- python - 如何使用python确定两个图中的峰值并仅绘制两个图中的峰值图
- node.js - 如何在 docker 容器中配置节点应用程序和 haProxy?
- postgresql - 根据条件拆分为多列
- java - Spring Boot JAR 应用程序未从资源文件夹中读取 chromedriver.exe
- hyper-v - Enable-PSRemoting (Set-WSManQuickConfig) 和 HyperV 适配器