Home > Software design >  how to formaStyle a row by index /rowname with datatable in shiny?
how to formaStyle a row by index /rowname with datatable in shiny?

Time:12-11

I'm doing a Shiny app and I have troubles to put some style and color.

I'm trying to put some color on my datatable : I want to color a specific row. the rowname of this row is "Sum".

I also wanted to color the column "Sum" and I succeed to do it : So I can color a specific column named "Sum" like this :

output$data_1<-renderDataTable(datatable(data(),options = list(dom = 't',pageLength=100))%>%formatStyle("Sum", backgroundColor = "orange")

But I don't know how i can do the same type of thing with my row ?

edit : my "Sum" row is not always the last row in my data.

Thank you for your help ! :)

EDIT :

A simple example :

library(shiny)
library(DT)

data_example<-data.frame("A"=c(40,10,20,10,5,85),"B"=c(10,20,10,20,5,65),"Sum"=c(50,30,30,30,10,150), row.names = c("1","2","3", "4", "5", "Sum"))

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Example"),
    dataTableOutput("table")

)

# Define server logic required to draw a histogram
server <- function(input, output) {

    output$table <- renderDataTable(datatable(data_example)%>%formatStyle("Sum", backgroundColor = "orange"))
}

# Run the application 
shinyApp(ui = ui, server = server)

enter image description here

EDIT :

Thanks to akrun , i finally find a way a generalisable expression to do it with all my table :

output$table <- renderDataTable(datatable(data_example)%>%formatStyle("Sum", backgroundColor = "orange")
                                    %>%formatStyle(0, target="row",backgroundColor =  styleEqual("Sum", "orange"))

CodePudding user response:

We may specify the index for rows as 0 in formatStyle, and use styleEqual to match and replace the 'cols1' created

server <- function(input, output) {
  v1 <- row.names(data_example)
  cols1 <- ifelse(v1 =='Sum','orange','')
  
  output$table <- renderDataTable(datatable(data_example)%>%
        formatStyle(0, target = "row",
                            backgroundColor = styleEqual(v1, cols1)))
}


shinyApp(ui = ui, server = server)

-output

enter image description here

CodePudding user response:

My solution according to @akrun answer ! ^^

  output$table <- renderDataTable(datatable(data_example)%>%formatStyle("Sum", backgroundColor = "orange")
                                        %>%formatStyle(0, target="row",backgroundColor =  styleEqual("Sum", "orange"))
  • Related