Reputation: 13
I am writing a shiny script where a file is uploaded, a dropdown appears with the column names from that file, and then a second dropdown appears with the unique values from the column in the file selected in the first dropdown. I was able to create the first dropdown, but am having trouble with the second dropdown. Here is my code thus far:
ui <- fluidPage(
titlePanel("File Upload Test"),
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose csv file",
multiple = T,
accept = c(".csv")),
uiOutput("y_input"),
uiOutput("target_input")),
mainPanel(
plotOutput("contents"))))
server <- function(input, output, session) {
inFile <- reactive({
if (is.null(input$file1)) {
return(NULL)
} else {
input$file1}
})
myData <- reactive({
if (is.null(inFile())) {
return(NULL)
} else {
read.csv(inFile()$datapath)}
})
output$y_input <- renderUI({
if (is.null(inFile())) {
return(NULL)
} else {
selectInput("y_output", "Select Y Variable", names(myData()))}
})
output$target_input <- renderUI({
if (is.null(input$y_input)) {
return(NULL)
} else {
selectInput("target_output", "Select Target Group",
myData( [,input$y_output])}
})
}
Any help here is appreciated! This is my first post on stack overflow, so if there are any formatting or clarity things in this post I can/should fix please let me know! Thanks!
Upvotes: 1
Views: 3261
Reputation: 4072
req
req(name_of_input)
is shorthand for if(is.null(name_of_input)) return NULL
. It will save you a few strokes while providing better readability.
inFile
is unnecessaryUse input$file1$datapath instead. Again this is more concise while having better performance as well.
myData <- reactive({
req(input$file1)
read.csv(input$file1$datapath)
})
Your reference to myData
is wrong. The subsetting part of [,input$y_output]
should be outside of the parentheses, like this: myData()[,input$y_output]
. Keep in mind that even though reactives
look like functions they don't take any arguments.
server <- function(input, output, session) {
myData <- reactive({
req(input$file1)
read.csv(input$file1$datapath)
})
output$y_input <- renderUI({
req(input$file1)
selectInput("y_output", "Select Y Variable", names(myData()))
})
output$target_input <- renderUI({
req(input$file1)
selectInput("target_output", "Select Target Group",
myData()[,input$y_output]
)
})
}
ps: Welcome to stackoverflow! :)
Upvotes: 5