0
votes

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)?

I found this: How to pre-select cells in Shiny DT datatables

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.

1

1 Answers

2
votes

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

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

Solution:

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. 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.

For target = 'cell', it should be a matrix of two columns: the first column is the row indices of selected cells, and the second column is the column indices. -- From DT Github

Solution:

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
    )
  }
)

Update

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

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.