微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 R 中的“huxtable”库为表格中所需的单元格着色哪种方法更优雅?

如何解决如何使用 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 文档之后,它给了我以下内容(作为屏幕截图):

table

这就是我需要得到的。但是,我的问题是:有什么比编写这样的代码字符串更优雅的方法呢?我试着这样做:

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

当通过 [ 单个参数索引数组时,我可以是一个矩阵 许多列,因为有 x 的维度;结果是一个向量 具有与 i 的每一行中的索引集相对应的元素。

或者如果你想变得很酷:

diag(background_color(sample_df[-1,])) <- "grey"

我很惊讶这行得通:-)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。