0
votes

I have created a DataTable in shiny within which the user has the option to select whether an ID should be considered as Dependent, Independent or None. I have attached a reproducible example for convenience. If you run the App, by default, all Id's are classified as Independent. What i am next trying to do next but currently unsuccessful is that the selection corresponding to ID 3 should be by default Dependent. I am using a selectInput for each of the rows in the dataTable. Can someone help me understand how can i make one particular ID as dependent and rest as independent by Default. When the user then runs the App he can changes the selection under ID's according to his need using the selectInputs.

library(shiny)
library(DT)


ui = fluidPage(
  DT::dataTableOutput('x1'),
)

server = function(input, output, session) {

# Helper function for making checkbox
  shinyInput = function(FUN, len, id,...) {
    inputs = character(len)
    for (i in seq_len(len)) {
      inputs[i] = as.character(FUN(paste0(id, i), label = NULL, ...))
    }
    inputs
}

# helper function for reading selections
  shinyValue = function(id, len) {
    unlist(lapply(seq_len(len), function(i) {
      value = input[[paste0(id, i)]]
      if (is.null(value)){
        NA
      } else {
        value
      }
    }))
}


n = 5

df = data.frame(ID = seq_len(n),
      selection = shinyInput(selectInput, n, 'cb_', choices=c("Independent","Dependent","None")),
      month = month.abb[1:n],
      stringsAsFactors = FALSE)


output$x1 = DT::renderDataTable({
      df},
      escape = FALSE, selection = 'none',
      options = list(
        dom = 't', paging = FALSE, ordering = FALSE,
        preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
        drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
      ),rownames=FALSE)


}

shinyApp(ui = ui,server = server)
1

1 Answers

1
votes

From ?selectInput

selected The initially selected value (or multiple values if multiple = TRUE). If not specified then defaults to the first value for single-select lists and no values for multiple select lists.

So by default selectInput will choose the first value as the default value, so we need to change the default value when i=3 i.e ID=3

# Helper function for making checkbox
shinyInput = function(FUN, len, id,...) {
  #browser()
  inputs = character(len)
  for (i in seq_len(len)) {
    if(i!=3){
      inputs[i] = as.character(FUN(paste0(id, i), label = NULL, ...))
    } else {
      inputs[i] = as.character(FUN(paste0(id, i), label = NULL, selected = "Dependent",...))
    }
  }
  inputs
}