简体   繁体   English

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

[英]How to color the required cells in the table using "huxtable" library in R. Which is more elegant way to do it?

I need to mark some special cells in the table with a gray color.我需要用灰色标记表格中的一些特殊单元格。 Something like this:像这样的东西:

```{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")
```

And after "knitr" as HTML document it gives me the following (as a screenshot):在“knitr”作为 HTML 文档之后,它给了我以下信息(作为屏幕截图):

桌子

And that's what i need to get.这就是我需要得到的。 BUT, my question is: What is more elegant way to do it instead of writing such strings of code?但是,我的问题是:有什么比编写这样的代码字符串更优雅的方法呢? I tried to do it like this:我试着这样做:

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()

... And it doesn't give me any result at all. ...而且它根本没有给我任何结果。 Any ideas?有任何想法吗?

You can use the old-school interface and a little-known fact about R subsetting:您可以使用老式界面和关于 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

From ?Extract :?Extract

When indexing arrays by [ a single argument i can be a matrix with as many columns as there are dimensions of x;当通过 [ 索引 arrays 时,单个参数 i 可以是具有与 x 维数一样多的列的矩阵; the result is then a vector with elements corresponding to the sets of indices in each row of i.结果是一个向量,其元素对应于 i 的每一行中的索引集。

Or if you want to be really cool:或者,如果你想变得很酷:

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

I'm amazed this worked:-)我很惊讶这有效:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM