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

136 views Asked by At

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

table

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?

1

There are 1 answers

4
dash2 On BEST ANSWER

You can use the old-school interface and a little-known fact about R subsetting:

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:

When indexing arrays by [ a single argument i can be a matrix with as many columns as there are dimensions of x; the result is then a vector with elements corresponding to the sets of indices in each row of i.

Or if you want to be really cool:

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

I'm amazed this worked :-)