Change RenderTable Row Color with if-else condition

Viewed 21

I am writing a RenderTable, and I want to change the color of the row with if condition.

### I need txt0 to determine which output table should I highlight, and MASE_name[best_model_index] to determine which model to highlight
  output$recommended_model <- renderPrint({
    if (is.null(runbutton_hit2_2())) return()
    if(best_model_index>5)
      txt0<<-paste0(" (Rate - based.)")
    else
      txt0<<-paste0(" (Number - based.)")
    paste0("The most recommended model is ",MASE_name[best_model_index],txt0)

  })

###Table 1
  output$Table_Number <- renderTable({

    predict_table_1<<-NULL
    predict_table_1<<-data.frame(matrix(ncol = 4, nrow = 5))
    #calculation process
    predict_table_1
  })

###Table 2
  output$Table_Rate <- renderTable({

    predict_table_2<<-NULL
    predict_table_2<<-data.frame(matrix(ncol = 4, nrow = 5))
    #calculation process
    predict_table_2
  })

The output$Table_Number & output$Table_Rate look like: enter image description here

What I want to do is, when txt0 is (Number - based.) and MASE_name[best_model_index] is A, I will change the color of the output$Table_Number => row A to color Red.

If txt0 is (Rate - based.) and MASE_name[best_model_index] is C, I will change the color of the output$Table_Rate => row C to color Red.

Thank you guys for answering! :)

1 Answers

I strongly recommend using DT package (https://rstudio.github.io/DT/). I'll demonstrate on Table_Rate table.

# add DT package at the top
library(DT)
...
# change from tableOutput("Table_Rate) to DTOutput(outputId = "Table_Rate")
# change render code 
output$Table_Rate <- DT::renderDT({
 datatable(df) %>% 
  formatStyle(
   'Model',
   target = 'row',
   backgroundColor = styleEqual(MASE_name[best_model_index], 'red')
   )
})

Whole article for styling using DT is here

Related