Imran Ali Imran Ali - 8 days ago 6
R Question

how to display elements of a character vector one by one

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

Answer

The problem is:

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.

Solution:

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.

So check:

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
  })
})
Comments