-->

How do I make the choices in radioButtons reactive

2019-08-03 21:27发布

问题:

This is what I have and I think the problem is that the ui.R runs first, so the function progs() isn't defined (or I don't know how to do reactive functions). My error looks like this:

Error in lapply(obj, function(val) { : could not find function "progs"

and my code looks like this:

ui.R

library(shiny)
progs <- list.files("C:/Users/OIT-Classroom/Desktop/ODP/Report 1/aggregate/")
progs <- gsub('.{6}$', '', progs)

shinyUI(bootstrapPage(
  tabsetPanel(id="Reports",
              tabPanel("Report 1",
                       sidebarPanel(
                         p("text"),
                         radioButtons("choices", choices = progs(), label = "Programs")
                      ),
                       mainPanel(
                         tableOutput('age')
                       )
              ),
              tabPanel("Report 2",
                       sidebarPanel(
                         p("text"),
                         radioButtons("choices", choices = progs(), label = "Programs")
                       ),
                       mainPanel(
                         tableOutput('psc5'),
                         plotOutput('psc5p'),
                       )
              ) 
  )
))

server.R

library(shiny)

shinyServer(function(input, output, session) {

  progs <- reactive({
    progs <- list.files(paste("C:/Users/OIT-Classroom/Desktop/ODP/", input$Reports, "/aggregate/", input$choices, ".RData", sep = ""))
    gsub('.{6}$', '', progs)
  })

  output$age <- function(){
    paste(knitr::kable(
      age, format = 'html', output = FALSE,
      table.attr="class='data table table-bordered table-condensed'"),
      sep = '\n')
  }
  output$psc5 <- function(){
    paste(knitr::kable(
      psc5, format = 'html', output = FALSE,
      table.attr="class='data table table-bordered table-condensed'"),
      sep = '\n')
  }
  output$psc5p <- renderPlot({
    plot(psc5[, 2:3], type="b", ylim=c(0, 40), ylab="", xaxt="no", xlab="", col="red", main="Figure 2: Problem Severity Comparison of Mean Scores for Children Ages 5+", cex.main=0.8, cex.axis = 0.8, font.main = 1, family="serif")
    par(new = T)
    axis(1, at=1:2, labels=c("Intake", "Discharge"), col.axis="black", las=1, cex.axis =0.8)
  })
})

回答1:

I'm assuming you're trying to automatically update the choices for the radio buttons. The progs function you are trying to call isn't defined in the UI script so that's where your error is coming from. Try using the observe and updateRadioButtons functions somewhere in your server script. Might look something like this:

observe({
  updateRadioButtons(session, "choices", choices = progs())
})

If you then go into your UI script and change the progs() part of the radio buttons definition to just progs it should work off the progs variable you defined at the beginning of the UI. I can't test all of this, since I don't have the files, but it should get you close.