I have a character vector corpus
. I am trying to display each member of the vector one by one as I click the Next
button. How can I increment the current
variable using Next
button?
So far I have the following code:
#ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("Display character vector one by one"),
sidebarLayout(sidebarPanel(actionButton("Next", "Next Sentence")),
mainPanel( htmlOutput("content"))
)))
#server.R
shinyServer(function(input, output) {
corpus <- c("Sample sentence one", "Second sentence", "Third sentence")
current <- 1
observeEvent(input$Next,{
if(current <= length(corpus))
output$content <- renderText(corpus[current])
})
})
Please also suggest if there are better ways to achieve this functionality
In your server.R
, you make the variable current
local, so every time you click the button Next Sentence , it remains constantly 1
, as a result, it will always render the first element in your list, which is Sample sentence one
.
Make a global variable, increase by 1
after every time you click the button. In RShiny , use <<-
to modify global variable instead of <-
. Also check Scoping rules for Shiny apps .
current <- 0
shinyServer(function(input, output) {
corpus <- c("Sample sentence one", "Second sentence", "Third sentence")
observeEvent(input$Next,{
if(current <= length(corpus))
output$content <- renderText(corpus[current])
current <<- current %% length(corpus) + 1
})
})
You can try this too, store the current index as reactive value and show the sentences circularly, with modulo arithmetic:
#ui.R
library(shiny)
ui <- shinyUI(fluidPage(
titlePanel("Display character vector one by one"),
sidebarLayout(sidebarPanel(actionButton("Next", "Next Sentence")),
mainPanel( htmlOutput("content"))
)))
#server.R
server <- shinyServer(function(input, output) {
values <- reactiveValues()
values$current <- 0
corpus <- c("Sample sentence one", "Second sentence", "Third sentence")
observeEvent(input$Next,{
output$content <- renderText(corpus[values$current])
values$current <- values$current %% length(corpus) + 1
})
})
shinyApp(ui = ui, server = server)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.