I am trying to show a table with different background based on a particular column value.
So, I want to group by column A and based on that if Column D has NULL value then the background is set accordingly.
Case 1: if it has NULL as well as other values : Color yellow
Case 2: No NULLs (All Data): Color Red
Case: All NULLs: Color Green
I have this code here to achieve this but for some reason the grouping is failing and it takes one single color: Yellow to the whole tables background because it is only checking the count of NULLs based on D column and not grouping by A to do this. Please help!
# DataDFQuery is a sql query which has all the 4 columns as an output
DataDF <- DataDFQuery %>% dplyr::group_by(A)
functiontocheck <- function(A,D)
{
for (u in 2:length(A)) # Looping through all the A
{
for (e in 2:length(D)) #Looping through the D within those A
{
TotalCount <- length(D) #Length of the error column within the A
NULLCount <- sum(str_detect(D, '^NULL')) #Length of the "NULL" within the column
# Assigning the color coding based on these lengths of D
if (NULLCount == TotalCount)
{DataTableBackground = 'lightgreen'}
else if (NULLCount < TotalCount)
{DataTableBackground = 'lightyellow'}
else if (NULLCount == 0)
{DataTableBackground = '#FFCCCB'}
}
}
return(DataTableBackground)
}
output$DataDF <- DT::renderDataTable(
DataDF %>%
datatable(rownames= FALSE
)
)%>%
formatStyle(colnames(DataDF), target = 'row', backgroundColor = functiontocheck(A, D))
)
Below is a slightly different approach. First, I use a case_when() statement to create a column in the data frame named color_level. Then, the colors are assigned to backgroundColor using the styleEqual() function, specifying the levels and associated values.
A quick question is there a way to add legend to this table as well? Like if would like to add a small table or box with color coding specification what red, yellow and green mean?
I know there is a way to add legends to plots/graphs. Do you know if it exists for such tables as well?
I'm not aware of any legends that can be added to a table, but you could utilize the table caption (and HTML) to specify what the colors mean. Below is one way to do that.
Thanks again @scottyd22 , I believe I might have missed something because if I try another hex code for the colors it stops showing the box and the color on the UI.
Here I used #FFCCCB instead of the red color you mentioned in your example