vendredi 15 mars 2019

R: create a for loop to assign different colors to cell_spec (kable)

I'm using kable to create tables for about 500 data-sets, hence, I'm trying to create one script and loop over it. I'm trying to use cell_spec to color the background of cells according another column which will certainly change in number and type between data sets so I want to take this into account. How can one set up an R script to take this into account.

Here is my script currently using a normal loop inside the kable command which doesn't work. As I understand it only one cell_type command is allowed.

[the dataset grps is predefined criteria to determine groups]

For the code below, color dataset is below.

color <- structure(list(color = c("#D2A8A4", "#2C5280", "#9DADCD", "#FFCF77", 
"#FFD892")), .Names = "color", row.names = c(NA, 
-6L), class = "data.frame")


mtcars[1:5,1:4] %>%
    mutate(
      mpg = cell_spec(mpg, color="black"),
      cyl = cell_spec(cyl, color="black"),
      hp = for(g in 1:nrows){ifelse(hp[g] == hp[g],cell_spec(hp[g], background=color[g,1],background_as_tile=T),cell_spec(hp, background=''))} %>%
    knitr::kable(format="html")%>% 
    kable_styling("striped", full_width = F)

Aucun commentaire:

Enregistrer un commentaire