renderDataTable Select all cells containing value > 10 and highlight

限于喜欢 提交于 2019-12-25 10:20:15

问题


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");}
               }')

回答1:


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");
        });
    }'
)



回答2:


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");',
          '});',
          '}')
      ))
    })
  }

)

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.



来源:https://stackoverflow.com/questions/29631659/renderdatatable-select-all-cells-containing-value-10-and-highlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!