Charles Woodson
Charles Woodson

Reputation: 39

R Shiny - Passing data into drop-down input selector

I'm trying to create a drop-down selector in Shiny. The Shiny tutorial has this code in ui.r:

selectInput("var", 
    label = "Choose a variable to display",
    choices = c("Percent White", "Percent Black",
      "Percent Hispanic", "Percent Asian"),
    selected = "Percent White"),

If I go into RStudio and write:

myVar = c("Percent White", "Percent Black",
          "Percent Hispanic", "Percent Asian") 

myVar is of type chr.

In my project, I want to load an .RData object in server.r. When I run:

mydata = load("myDataFile.RData")

mydata is then of type chr and contains the name of all the objects within the .RData file.

I want to have a drop-down select from everything in mydata (the names of the objects in my .RData file). I'm having trouble passing this mydata list from server.r to ui.r.

If I do anything in server.r like

output$myChoices = c(mydata)
output$mydat = mydata 

and in ui.r like

choices = mydata,
choices = output$mydata,
or choices = "mydata",

I either get that it doesn't recognize mydata or the only choice available in the dropdown is literally "mydata."

Also, the following successfully prints out all the objects within mydata:

#server.r:
output$text4 <- renderText({ 
      paste(mydata)
    })

#ui.r:
textOutput("text4"),

It makes sense how "mydata" would literally print "mydata," but that's the syntax to print the text.

Again, I want a drop down to choose from everything within mydata.

Thanks so much for the help!

Upvotes: 2

Views: 1370

Answers (1)

NicE
NicE

Reputation: 21443

All the info you need to create the selectInput is in the server.R part so you could use uiOutput/renderUi to create it there.

You could for example add uiOutput("select_data") in your ui.R and in server.R:

output$select_data <- renderUi({
selectInput("choose_data", 
    label = "Choose data",
    choices = mydata
    ) 
})

You can then access what the user has chose in server.R using input$select_data

Upvotes: 2

Related Questions