“Next” button in a R Shiny app

2020-07-13 13:00发布

I'm trying to build an step by step app using Shiny. My aim is creating an examen consisting in a bunch of questions written in a database. What I need is a "next" button which when you click another question shows up.

I've been triying with an "action button" but it just works the first time, that is, the first time that it is clicked a question shows up, but it becomes unclickable once clicked for first time (it doesn't work as a "next button" as I wish).

Here is the code:

Server.R:

library(xlsx)
data<-read.xlsx("data/base.xlsx",sheetName="Full1")

shinyServer(function(input, output) {

  data[,2]<-as.character(data[,2])

  question<-data[2,2]

  ntext <- eventReactive(input$goButton, {
    question
  })

  output$nText <- renderText({
     ntext()
  })  
})

ui.R:

shinyUI(pageWithSidebar(
  headerPanel("Exam"),
  sidebarPanel(
    actionButton("goButton", "Next"),
    p("Next Question")
  ),
  mainPanel(
    verbatimTextOutput("nText")
  )
))

Thank you so much.

标签: r shiny
1条回答
狗以群分
2楼-- · 2020-07-13 13:38

You can do something like this. Please note the comments in the code

rm(list = ls())
library(shiny)
questions <- c("What is your name?","Can you code in R?","Do you find coding fun?","Last Question:How old are you?")

ui <- pageWithSidebar(
  headerPanel("Exam"),
  sidebarPanel(actionButton("goButton", "Next"),p("Next Question")),
  mainPanel(verbatimTextOutput("nText")))

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

  # Inititating reactive values, these will `reset` for each session
  # These are just for counting purposes so we can step through the questions
  values <- reactiveValues()
  values$count <- 1

  # Reactive expression will only be executed when the button is clicked
  ntext <- eventReactive(input$goButton,{

    # Check if the counter `values$count` are not equal to the length of your questions
    # if not then increment quesions by 1 and return that question
    # Note that initially the button hasn't been pressed yet so the `ntext()` will not be executed
    if(values$count != length(questions)){
      values$count <- values$count + 1
      return(questions[values$count])
    }
    else{
      # otherwise just return the last quesion
      return(questions[length(questions)])
    }
  })

  output$nText <- renderText({
    # The `if` statement below is to test if the botton has been clicked or not for the first time,
    # recall that the button works as a counter, everytime it is clicked it gets incremented by 1
    # The initial value is set to 0 so we just going to return the first question if it hasnt been clicked
    if(input$goButton == 0){
      return(questions[1])
    }
    ntext()
  })  
}
shinyApp(ui = ui, server = server)
查看更多
登录 后发表回答