从Shiny App中的DataTable获取选定的行

时间:2022-09-17 10:58:47

I want to modify this application:

我想修改这个应用程序:

https://demo.shinyapps.io/029-row-selection/

https://demo.shinyapps.io/029-row-selection/

so that only one row can be selected at a time, and so that I can acquire the item in the first column of the selected row to plot data with. Does anyone know how to do this?

这样一次只能选择一行,这样我就可以获取所选行的第一列中的项目来绘制数据。有谁知道如何做到这一点?

4 个解决方案

#1


16  

UPDATE: you can now access the selected rows using input$tableId_rows_selected in server.R. See here for more details.

更新:您现在可以使用server.R中的输入$ tableId_rows_selected访问所选行。有关详细信息,请参见此处

To select a unique row, you can change the callback function of your example to this:

要选择唯一的行,可以将示例的回调函数更改为:

callback = "function(table) {
      table.on('click.dt', 'tr', function() {
            table.$('tr.selected').removeClass('selected');
            $(this).toggleClass('selected');            
        Shiny.onInputChange('rows',
                            table.rows('.selected').data()[0][0]);
      });
    }"

When you click on a row,it basically removes any selected rows (they have the .selected class) and selects the row you clicked on.

当您单击某一行时,它基本上会删除所有选定的行(它们具有.selected类)并选择您单击的行。

I also changed the code in the Shiny.onInputChange function so that it returns the number in the first column.

我还更改了Shiny.onInputChange函数中的代码,以便它返回第一列中的数字。

#2


9  

The R method which renders a DataTable has a parameter which defines the selection mode. For example:

呈现DataTable的R方法具有定义选择模式的参数。例如:

output$table1 <-
  DT::renderDataTable(dataSet,
                      selection = 'single')

Possible values are ('multiple' is the default):

可能的值是('multiple'是默认值):

  • none
  • 没有
  • single
  • multiple

For further reference you can see: http://rstudio.github.io/DT/shiny.html

有关进一步参考,请参阅:http://rstudio.github.io/DT/shiny.html

EDIT 04/14/2016

编辑2016年4月14日

In the setup I use working with single selection mode has issues.

在我使用单一选择模式的设置中存在问题。

Here is what version I use:

这是我使用的版本:

> DT:::DataTablesVersion
[1] "1.10.7"
> packageVersion("DT")
[1] ‘0.1’

The problem I faced is that visually you have a single row selection but when you do:

我面临的问题是视觉上你有一行选择,但是当你这样做时:

observeEvent(input$table1_rows_selected, {
  str(input$table1_rows_selected)
})

You will get a list with all rows which were selected but were not explicitly deselected. In other words selecting a new row does not automatically deselect the previous row in the internal Datatables logic. This might be also due to the DT wrapper, not sure.

您将获得一个列表,其中包含已选中但未明确取消选择的所有行。换句话说,选择新行不会自动取消选择内部Datatables逻辑中的上一行。这可能也是由DT包装器引起的,不确定。

This is why currently as a workaround we use JS for this:

这就是为什么我们目前使用JS作为解决方法的原因:

$(document).on('click', '#table1 table tr', function() {
    var selectedRowIds = $('#table1 .dataTables_scrollBody table.dataTable').DataTable().rows('.selected')[0];

    var selectedId = "";
    if (selectedRowIds.length === 1) {
        selectedId = $(this).children('td:eq(0)').text();
    } else {
      $('#table1 tbody tr').removeClass('selected');
    }
    Shiny.onInputChange("table1_selected_id", selectedId);
});

Once you have this in place you will be able to do:

一旦你有了这个,你将能够做到:

observeEvent(input$table1_selected_id, {
  str(input$table1_selected_id)
})

This now at least sends correct data to your server.R code. Unfortunately you will still have an issue with the table because internally it keeps track on which rows were selected and if you switch pages it will restore a wrong selection. But at least this is purely a visual defect and your code will have the chance to function properly. So this solution actually needs more work.

现在至少将正确的数据发送到您的服务器.R代码。不幸的是,您仍然会遇到表的问题,因为在内部它会跟踪选择哪些行,如果您切换页面,它将恢复错误的选择。但至少这纯粹是一个视觉缺陷,你的代码将有机会正常运行。所以这个解决方案实际上需要更多工

#3


1  

This is not a direct solution to the example you have posted, however gives answer with another example.

这不是您发布的示例的直接解决方案,但是给出了另一个示例的答案。

There is a downloadable shiny app example given and discussed in the following link, click here! for selecting single row in a table using a class parameter.

在下面的链接中给出并讨论了可下载的闪亮应用示例,请单击此处!使用类参数选择表中的单行。

#4


-1  

The below code display a dataframe in DT table format. Users will be able to select single row. The selected row is retrieved and displayed. you can write your plot function in the plot block in the server.

以下代码以DT表格式显示数据帧。用户将能够选择单行。检索并显示所选行。您可以在服务器的绘图块中编写绘图功能。

I hope this helps !!

我希望这有帮助 !!

         # Server.R
         shinyServer(function(input, output,session) {




          output$sampletable <- DT::renderDataTable({
          sampletable
          }, server = TRUE,selection = 'single')  

          output$selectedrow <- DT::renderDataTable({

          selectedrowindex <<-     input$sampletable_rows_selected[length(input$sampletable_rows_selected)]
         selectedrowindex <<- as.numeric(selectedrowindex)
         selectedrow <- (sampletable[selectedrowindex,])
         selectedrow



           })

          output$plots <- renderPlot({

          variable <- sampletable[selectedrowindex,1]
          #write your plot function


              })


          })

          #ui.R 
          shinyUI(navbarPage( "Single Row Selection",



                tabPanel("Row selection example",
                         sidebarLayout(sidebarPanel("Parameters"),
                             mainPanel(
                               DT::dataTableOutput("selectedrow"),   
                             DT::dataTableOutput("sampletable")

                           ))

                      )

                      ))

         # global.R 

        library(DT)
        library(shiny)
        selectedrowindex = 0

#1


16  

UPDATE: you can now access the selected rows using input$tableId_rows_selected in server.R. See here for more details.

更新:您现在可以使用server.R中的输入$ tableId_rows_selected访问所选行。有关详细信息,请参见此处

To select a unique row, you can change the callback function of your example to this:

要选择唯一的行,可以将示例的回调函数更改为:

callback = "function(table) {
      table.on('click.dt', 'tr', function() {
            table.$('tr.selected').removeClass('selected');
            $(this).toggleClass('selected');            
        Shiny.onInputChange('rows',
                            table.rows('.selected').data()[0][0]);
      });
    }"

When you click on a row,it basically removes any selected rows (they have the .selected class) and selects the row you clicked on.

当您单击某一行时,它基本上会删除所有选定的行(它们具有.selected类)并选择您单击的行。

I also changed the code in the Shiny.onInputChange function so that it returns the number in the first column.

我还更改了Shiny.onInputChange函数中的代码,以便它返回第一列中的数字。

#2


9  

The R method which renders a DataTable has a parameter which defines the selection mode. For example:

呈现DataTable的R方法具有定义选择模式的参数。例如:

output$table1 <-
  DT::renderDataTable(dataSet,
                      selection = 'single')

Possible values are ('multiple' is the default):

可能的值是('multiple'是默认值):

  • none
  • 没有
  • single
  • multiple

For further reference you can see: http://rstudio.github.io/DT/shiny.html

有关进一步参考,请参阅:http://rstudio.github.io/DT/shiny.html

EDIT 04/14/2016

编辑2016年4月14日

In the setup I use working with single selection mode has issues.

在我使用单一选择模式的设置中存在问题。

Here is what version I use:

这是我使用的版本:

> DT:::DataTablesVersion
[1] "1.10.7"
> packageVersion("DT")
[1] ‘0.1’

The problem I faced is that visually you have a single row selection but when you do:

我面临的问题是视觉上你有一行选择,但是当你这样做时:

observeEvent(input$table1_rows_selected, {
  str(input$table1_rows_selected)
})

You will get a list with all rows which were selected but were not explicitly deselected. In other words selecting a new row does not automatically deselect the previous row in the internal Datatables logic. This might be also due to the DT wrapper, not sure.

您将获得一个列表,其中包含已选中但未明确取消选择的所有行。换句话说,选择新行不会自动取消选择内部Datatables逻辑中的上一行。这可能也是由DT包装器引起的,不确定。

This is why currently as a workaround we use JS for this:

这就是为什么我们目前使用JS作为解决方法的原因:

$(document).on('click', '#table1 table tr', function() {
    var selectedRowIds = $('#table1 .dataTables_scrollBody table.dataTable').DataTable().rows('.selected')[0];

    var selectedId = "";
    if (selectedRowIds.length === 1) {
        selectedId = $(this).children('td:eq(0)').text();
    } else {
      $('#table1 tbody tr').removeClass('selected');
    }
    Shiny.onInputChange("table1_selected_id", selectedId);
});

Once you have this in place you will be able to do:

一旦你有了这个,你将能够做到:

observeEvent(input$table1_selected_id, {
  str(input$table1_selected_id)
})

This now at least sends correct data to your server.R code. Unfortunately you will still have an issue with the table because internally it keeps track on which rows were selected and if you switch pages it will restore a wrong selection. But at least this is purely a visual defect and your code will have the chance to function properly. So this solution actually needs more work.

现在至少将正确的数据发送到您的服务器.R代码。不幸的是,您仍然会遇到表的问题,因为在内部它会跟踪选择哪些行,如果您切换页面,它将恢复错误的选择。但至少这纯粹是一个视觉缺陷,你的代码将有机会正常运行。所以这个解决方案实际上需要更多工

#3


1  

This is not a direct solution to the example you have posted, however gives answer with another example.

这不是您发布的示例的直接解决方案,但是给出了另一个示例的答案。

There is a downloadable shiny app example given and discussed in the following link, click here! for selecting single row in a table using a class parameter.

在下面的链接中给出并讨论了可下载的闪亮应用示例,请单击此处!使用类参数选择表中的单行。

#4


-1  

The below code display a dataframe in DT table format. Users will be able to select single row. The selected row is retrieved and displayed. you can write your plot function in the plot block in the server.

以下代码以DT表格式显示数据帧。用户将能够选择单行。检索并显示所选行。您可以在服务器的绘图块中编写绘图功能。

I hope this helps !!

我希望这有帮助 !!

         # Server.R
         shinyServer(function(input, output,session) {




          output$sampletable <- DT::renderDataTable({
          sampletable
          }, server = TRUE,selection = 'single')  

          output$selectedrow <- DT::renderDataTable({

          selectedrowindex <<-     input$sampletable_rows_selected[length(input$sampletable_rows_selected)]
         selectedrowindex <<- as.numeric(selectedrowindex)
         selectedrow <- (sampletable[selectedrowindex,])
         selectedrow



           })

          output$plots <- renderPlot({

          variable <- sampletable[selectedrowindex,1]
          #write your plot function


              })


          })

          #ui.R 
          shinyUI(navbarPage( "Single Row Selection",



                tabPanel("Row selection example",
                         sidebarLayout(sidebarPanel("Parameters"),
                             mainPanel(
                               DT::dataTableOutput("selectedrow"),   
                             DT::dataTableOutput("sampletable")

                           ))

                      )

                      ))

         # global.R 

        library(DT)
        library(shiny)
        selectedrowindex = 0