dloudtrain
dloudtrain

Reputation: 301

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.

Upvotes: 3

Views: 5724

Answers (2)

mhovd
mhovd

Reputation: 4087

You can also use kableExtra::remove_column(), to remove a selected column from your final kable table.

For example, this will remove the first column from a table

library(kableExtra)
my_table = kable(mtcars)
remove_column(my_table, 1)

Upvotes: 2

Andrew Chisholm
Andrew Chisholm

Reputation: 6567

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

Upvotes: 4

Related Questions