renderDataTable Select all cells containing value

2019-09-14 04:20发布

I'm creating a dataTable that has a user-defined number of rows & columns. I would like to loop through all of the cells in the table (minus the first column, which contains names) and highlight/change CSS if values are greater than 10. Shiny has a great example of targeting a specific column (see below). I'm assuming I'd need to write some sort of jQuery function? I'm a complete jQuery newbie, so I gave it a try, and, it obviously hasn't worked (also see below). Any help would be greatly appreciated!

Shiny example of targeting a specific column:

rowCallback = I(
  'function(row, data) {
    // Bold cells for those >= 5 in the first column
    if (parseFloat(data[0]) >= 5.0)
      $("td:eq(0)", row).css("font-weight", "bold");
  }'
)

My failed attempt at writing a function to loop through cells:

rowCallback = I('
               function(row, data) {
               for each (i in 1:1000) {
               if (parseFloat(data[i]) > 10.0)
               $("td:eq(i)", row).css("color", "red");}
               }')

2条回答
等我变得足够好
2楼-- · 2019-09-14 04:56

Managed to implement it with this (without installing DT):

rowCallback = I(
    'function(row, data) {
        $("td", row).each(function(i) {
            if (i == 0) return; // first column is row names
            if (parseFloat(data[i]) >= 10.0)
                $(this).css("color", "red");
        });
    }'
)
查看更多
萌系小妹纸
3楼-- · 2019-09-14 05:00

for each (i in 1:1000) does not look like valid JavaScript syntax. Here is a minimal example using the DT package (the DataTables functions in shiny will be deprecated in future). It may be slightly difficult to understand if you are not familiar with JavaScript (our goal is to make it easier in future).

library(shiny)
library(DT)

shinyApp(

  ui = fluidPage(dataTableOutput('foo')),

  server = function(input, output) {
    output$foo = renderDataTable({
      datatable(iris, options = list(
        rowCallback = JS(
          'function(row, data) {',
          '$("td", row).each(function(i) {',
            'if (i == 0) return; // first column is row names',
            'if (parseFloat(data[i]) >= 3.0)',
              '$(this).css("color", "red");',
          '});',
          '}')
      ))
    })
  }

)

DT rowCallback

To install DT at this moment, you need:

install.packages(
  c("DT", "shiny")
  type = "source",
  repos = c("http://yihui.name/xran", "http://cran.rstudio.com")
)

You will be able to install everything normally from CRAN after DT is on CRAN.

查看更多
登录 后发表回答