[英]How to color the required cells in the table using "huxtable" library in R. Which is more elegant way to do it?
我需要用灰色標記表格中的一些特殊單元格。 像這樣的東西:
```{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
:
當通過 [ 索引 arrays 時,單個參數 i 可以是具有與 x 維數一樣多的列的矩陣; 結果是一個向量,其元素對應於 i 的每一行中的索引集。
或者,如果你想變得很酷:
diag(background_color(sample_df[-1,])) <- "grey"
我很驚訝這有效:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.