Alejandro Carrera
Alejandro Carrera

Reputation: 557

How to select variables from different data.frames in shiny?

I'm exploring shiny and I'm trying to do some app that does the following:

Code below:

df_list <- list(cars= mtcars, iris= iris)

ui <- fluidPage(


  titlePanel("Simple app"),

  sidebarLayout(

    sidebarPanel(

      selectInput("data", "Choose a database",
    choices=ls(df_list), selected=ls(df_list[1])),
    selectInput("xcol", "Variable X", names(data)),
    selectInput("ycol", "Variable Y", names(data))),

    mainPanel(

      plotOutput(outputId = "plot")

    )
  )
)



server <- function(input, output) {
    selectedData <- reactive( {
        data[, c(data$xcol, data$ycol)]
    })

    output$plot <- renderPlot({plot(selectedData())})
}

shinyApp(ui, server)

I feel I have two problems. The first one is pretty obvious since I can't make the app displays variables according to the data.frame selected. Second one is that I feel I'm missing something in my server function (I guess that's related with my first problem) so no plot is displayed.

Any help will be much appreciated.

Upvotes: 0

Views: 832

Answers (1)

YBS
YBS

Reputation: 21287

You had a few issues. The following should work.

df_list <- list("mtcars", "iris")

ui <- fluidPage(
  titlePanel("Simple app"),
  useShinyjs(),
  sidebarLayout(
    
    sidebarPanel(
      
      selectInput("data", "Choose a database",
                  choices=df_list, selected=df_list[[1]]),
      selectInput("xcol", "Variable X", c()),
      selectInput("ycol", "Variable Y", c())),
    
    mainPanel(
      
      plotOutput(outputId = "plot")
      ,DTOutput("t1")
    )
  )
)

server <- function(input, output, session) {
  
  mydata <- eventReactive(input$data, {
    get(input$data)
  })
  
  observeEvent(input$data, {
    req(mydata())
    choices <- names(mydata())
    updateSelectInput(session,"xcol",choices = choices, selected=choices[1])
    updateSelectInput(session,"ycol",choices = choices, selected=choices[2])
  }, ignoreNULL = FALSE)
  
  output$t1 <- renderDT({mydata()})
  
  output$plot <- renderPlot({
    req(mydata(),input$xcol,input$ycol)
    if (is.null(mydata()) | !(input$xcol %in% colnames(mydata())) | !(input$ycol %in% colnames(mydata())) ) {
      return(NULL)
    } else{
      selected_df <- mydata() %>% select(input$xcol, input$ycol)
      plot(selected_df)
    }
    
  })
}

shinyApp(ui, server)

Upvotes: 1

Related Questions