Search code examples
rknitrkableextra

R- knitr:kable - Is it possibe to hide selected columns?


I would like to create a table using knitr:kable in R where I am using several auxiliary columns for conditional formating.

The table (df_prices) looks like this:

device    price    competion_price  
A         20       23                 
B         158      160                
C         1000     999                

I am using the mutate and cell_spec for conditional formating just like this:

df_prices%>%
  mutate(price= cell_spec(
    price, color = "grey", bold = T,
    background = ifelse(price <= competion_price, green, red) %>%
  kable(escape = F, align = "c") %>%
  kable_styling(bootstrap_options = "striped", full_width = T, position = "left",font_size = 14) %>%
   collapse_rows(columns = c(1), valign = "middle") 

This works OK, but in the final output I would like to hide the column "competion_price" so that the output would look like this but with correct highlighting:

device    price    
A         20                      
B         158                     
C         1000       

Is something like this possible? Thank you very much for any suggestions.


Solution

  • Use dplyr::select with - to de-select a column like this.

    library(knitr)
    library(kableExtra)
    library(dplyr)
    df_prices <- read.table(text="device    price    competion_price  
    A         20       23                 
    B         158      160                
    C         1000     999", sep='',header=T)
    
    df_prices %>%   
        dplyr::mutate(price= cell_spec(price, color = "grey", bold = T, background = ifelse(price <= competion_price, 'green', 'red'))) %>%
        dplyr::select(-competion_price) %>%
        kable(escape = F, align = "c") %>%
        kable_styling(bootstrap_options = "striped", full_width = T, position = "left",font_size = 14) %>%
        collapse_rows(columns = c(1), valign = "middle") 
    

    (there are also a couple of fixes to the original code to make it work)

    enter image description here