duy ngọc
duy ngọc

Reputation: 65

R Shiny How to select input form data frame column (reactive)

I want to selectInput from reactive data frame column as code below but it is not showed anything:

library(shiny)
library(data.table)

ui <- fluidPage(
selectInput('region','Select region',choice=tableOutput('region'),selected=NULL)
)

server <- function(input, output, session){

data<- reactive(fread('murders.csv')) # this file contain 'region' column

output$region <- renderTable(data()$region)
}
shinyApp(ui = ui, server = server)

But when I read data outside server function (not reactive) the selectinput is working normal:

library(shiny)
library(data.table)

ui <- fluidPage(
selectInput('region','Select region',choice=data$region,selected=NULL)
)

data<- fread('murders.csv') # this file contain 'region' column

server <- function(input, output, session){

}
shinyApp(ui = ui, server = server)

I think it is better to read file in reactive mode in server function, could you show me how to select input from data column in reactive mode ?

Upvotes: 2

Views: 3080

Answers (1)

luismf
luismf

Reputation: 371

Unless you are planning on changing the murder csv file, there is no need for it to be reactive, and it can be a global value. If you are keen on it not being a global you can transform the ui in a function and load the data inside.

Version 1

library(shiny)
library(data.table)

ui <- function(request){
  data <- fread("murders.csv")
  fluidPage(
  selectInput('region','Select region',choice=data$region,selected=NULL)
)
}

server <- function(input, output, session){
}
shinyApp(ui = ui, server = server)

If you really want, by some reason, to load it inside the server what you are looking for is updateSelectInput. See version below

Version 2

library(shiny)
library(data.table)

ui <- fluidPage(
    selectInput('region','Select region',choices=NULL, selected=NULL)
  )

server <- function(input, output, session){
  data <- fread("murders.csv")
  updateSelectInput(session, "region", choices=data$region)
}
shinyApp(ui = ui, server = server)

And as I said there is no need for it to be reactive, but if you really want it to be reactive, you have to access the reactive inside a reactiveEnvironment, in this case observeEvent seems the most adequate:

Version 3

library(shiny)
library(data.table)

ui <- fluidPage(
  selectInput('region','Select region',choices=NULL, selected=NULL)
)

server <- function(input, output, session){
  data <- reactive(fread("murders.csv"))
  observeEvent(data(),updateSelectInput(session, "region", choices=data()$region))
}
shinyApp(ui = ui, server = server)

Upvotes: 4

Related Questions