-->

How to mark last row in results of DataTable using

2020-07-27 16:26发布

问题:

I would like to mark (for instance bold) the last row in Data Table generated using DT package. Let's say we have a table with the iris dataset:

library(DT)
datatable(iris)

Results:

So we have 150 rows and I would like to bold only 150 row.

Edit: @BigDataScientist let me clear this. I have this:

 output$tbl <- 
    DT::renderDataTable(
      data() %>% # let's say iris data - it doesn't matter
      bind_rows(summarise(data(), SUM = "SUM", A = sum(A), B = sum(B), 
                           C = sum(C), D = sum(D), 
                           E = sum(E), F = sum(F))) %>%
      mutate(SUM = rowSums(.[2:6])),
    extensions = 'Buttons', 
    options = list(
      dom = 'Blfrtip',
      lengthMenu = list(c(-1, 5, 10, 15, 20, 25), c('All', '5', '10', '15', '20', '25')),
      buttons = list('copy',
                     list(extend = 'excel',
                          filename = 'report'),
                     list(extend = 'pdf',
                          filename = 'report'),
                     'print'),
     rownames = FALSE,
     server = FALSE
    ) %>%
    formatStyle(
     target = "row",
     fontWeight = styleEqual(dim(.)[1], "bold")
    )
 )

So, I would like to add bolding last row; in this case, SUM of columns; to this pipeline, so everything would be in one piece (one pipeline).

回答1:

This page will help you, if you adapt the code a bit:

formatStyle(
  datatable(iris), 0, target = "row",
  fontWeight = styleEqual(dim(iris)[1], "bold")
)

Edit: It was asked (in addition) for the data to be passed as reactive() with pipes in Shiny. Well, i can only offer a workaround. I am not that familiar with pipes, especially how to pass several arguments.

shinyApp(
  ui = fluidPage(fluidRow(column(12, DT::dataTableOutput('tbl')))),
  server = function(input, output) {
    irisReact <- reactive(iris)
    dimIrisReact <- reactive(dim(iris)[1])    
    output$tbl = DT::renderDataTable(
      irisReact() %>% datatable() %>% formatStyle(
        0, target = "row",
        fontWeight = styleEqual(dimIrisReact(), "bold")
      )
    )
  }
)


回答2:

The solution by BigDataScientist failes when disabling rownames in datatable rownames = F.

If you want to hide the rownames and have the last row bold, a solution is to anyway set rownames = T and then hide them. This works for me:

library(DT)

data <- head(iris)

datatable(data, 
          rownames = T, # set rownames T
          options = list(columnDefs = list(list(visible = F, targets = 0)))) %>% # hide the rownames
  formatStyle(0, target = "row",
              fontWeight = styleEqual(dim(data)[1], "bold"))


回答3:

I addition to the answer from BigDataScientist I would also suggest to look at:

http://rstudio.github.io/DT/functions.html



标签: r shiny dt