【问题标题】:How to use renderDataTable in Shinny R's file upload example如何在 Shiny R 文件上传示例中使用 renderDataTable
【发布时间】:2015-01-07 09:08:25
【问题描述】:

我正在尝试创建我的第一个 Shiny R 应用程序,它做了两件事:

  1. 显示用户上传的 CSV 文件
  2. 统计用户选择的行数

为了实现这些功能,我需要结合file uploadrow selection这两个例子,其中涉及将renderTable切换为renderDataTable。但是,我只能使用renderDataTable 显示数据,但无法将callbackoptions 等参数传递给它。

这里是server.R代码

shinyServer(function(input, output) {
  output$contents <- renderDataTable({
    inFile <- input$file1
    if (is.null(inFile))
        return(NULL)
    subset(read.csv(inFile$datapath, header=input$header, sep=input$sep, quote=input$quote), select=input$show_vars)
  })
})

如果我在这种情况下(如下)更改上述功能,我会收到以下错误server.R:9:5: unexpected 'if'。我认为这与构建一个反应式文件上传应用程序有关,我找不到好的例子......谁能给我一些建议?谢谢!

shinyServer(function(input, output) {
  output$contents <- renderDataTable(
    inFile <- input$file1
    if (is.null(inFile))
      return(NULL)
   subset(read.csv(inFile$datapath, header=input$header, sep=input$sep, quote=input$quote), select=input$show_vars),
   options = list(pageLength = 10),
   callback = "function(table) {
         table.on('click.dt', 'tr', function() {
           $(this).toggleClass('selected');
           Shiny.onInputChange('rows',
                               table.rows('.selected').indexes().toArray());
         });
       }"
  )
})

【问题讨论】:

    标签: r shiny rstudio shiny-server


    【解决方案1】:

    renderDataTable 的第一个参数应该是一个表达式。您需要将代码用大括号括起来,以将第一部分代码作为表达式传递:

    shinyServer(function(input, output) {
      output$contents <- renderDataTable({
        inFile <- input$file1
        if (is.null(inFile))
          return(NULL)
        subset(read.csv(inFile$datapath, header=input$header, sep=input$sep, quote=input$quote), select=input$show_vars)
      }
      , options = list(pageLength = 10),
      , callback = "function(table) {
             table.on('click.dt', 'tr', function() {
               $(this).toggleClass('selected');
               Shiny.onInputChange('rows',
                                   table.rows('.selected').indexes().toArray());
             });
           }"
      )
    })
    

    【讨论】:

    • 感谢它运行良好。我想我的下一步是修改回调函数。有没有关于在 Shiny R 中包装 JavaScript 函数的参考书? (或者我想使用 jQuery 来修改 DOM 会容易得多)。
    • 我认为当前的 javascript 看起来可以计算用户选择的行数。一个闪亮的变量input$rows 现在将在server.R 中可用。它是一个向量,包含用户选择的行的索引。用户选择的行数将为length(input$rows)
    • 是的,我同意。但是我的数据有一个名为“study”的列,它有多个记录。所以我需要选择同一个研究中的所有记录。我可以在 jQuery 中轻松做到这一点,但需要找出 Shiny R 中的解决方案。谢谢。
    猜你喜欢
    • 2014-09-27
    • 1970-01-01
    • 2015-10-07
    • 2018-10-07
    • 2017-11-26
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多