本文介绍了用一栏预选Shiny app数据表中的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Shiny应用程序中有一个数据表输出,想要预选它的第一个单元格。我在下面创建了一个非常简单的示例,其中一栏和目标单元格作为选择选项。

I have an data table output in my Shiny app and want to pre-select the first cell of it. I created a very simple example below with one column and the target cell as selection option.

library(DT)
shinyApp(

  ui = fluidPage(
    fluidRow(
      h1('Data table'),
      DT::dataTableOutput('tab')

    )
  ),

  server = function(input, output, session) {
     col1 = c('Car', 'Truck', 'Bike') 
     df = data.frame(col1)

     output$tab = DT::renderDataTable(
        df, server = FALSE,
        selection = list(mode = 'single',target="cell"), 
        rownames= FALSE
    )
  }
)

我该怎么办(在这种情况下)预选第一个单元格(汽车)?

How can I (in this case) pre-select the first cell (Car)?

我发现了这一点:

在此帖子,我读到我必须使用矩阵作为选择标准,但在我的示例中我无法弄清它。

In this post I read that I have to use a matrix as selection criteria, but I am not able to get it right i my example.

推荐答案

有两种方法可以解决此问题,因为您的DT仅包含1列。

There are two ways to solve this problem since your DT only contains 1 column.


  1. 您可以使用 target ='row'(因为您只有1列,因此每一行只有1个单元格。)

  1. You can have target = 'row' (works since you only have 1 column, so each row is only 1 cell).

解决方案:

library(DT)
shinyApp(

  ui = fluidPage(
    fluidRow(
      h1('Data table'),
      DT::dataTableOutput('tab')

    )
  ),

  server = function(input, output, session) {
    col1 = c('Car', 'Truck', 'Bike') 
    df = data.frame(col1)

    output$tab = DT::renderDataTable(
      df, server = FALSE,
      selection = list(mode = 'single',target="row", selected = 1), 
      rownames= FALSE
    )
  }
)




  1. 您可以拥有 target ='cell'。在这种情况下,您必须创建第一个单元格的矩阵,这里的技巧是知道列索引在DT中从0开始。

  1. You can have target = 'cell'. In this case you have to create a matrix of the first cell and the trick here is knowing the column index starts at 0 in DT.



解决方案:

library(DT)
shinyApp(

  ui = fluidPage(
    fluidRow(
      h1('Data table'),
      DT::dataTableOutput('tab')

    )
  ),

  server = function(input, output, session) {
    col1 = c('Car', 'Truck', 'Bike') 
    df = data.frame(col1)

    output$tab = DT::renderDataTable(
      df, server = FALSE,
      selection = list(mode = 'single',target="cell", selected = matrix(c(1, 0), nrow = 1, ncol = 2)), 
      rownames= FALSE
    )
  }
)

更新

来自OP的评论, input $ tab_cell_clicked 为空白,因为预选择不会生成 click 操作。

From OP's comments, input$tab_cell_clicked is blank since pre-select does not generate a click action.

要获得此效果,只需为此添加 if语句效果。

To get this effect, simply add an if statement for this affect.

click = ifelse(input$tab_cell_clicked == "", col1[1], input$tab_cell_clicked)

**这未经测试,但是有想法。

**This is untested but the idea is there.

这篇关于用一栏预选Shiny app数据表中的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 04:07