1
votes

I want to create a vector by using observe() in R shiny. In the code blow, how can I create a vactor where all the input$n are concatenated. At the present time, I can only display a single value but could not concatenate and display all the inputs from the sliderInput.

ui.R

library(shiny)

fluidPage(
    titlePanel("Observer demo"),
    fluidRow(
            column(4, wellPanel(
                    sliderInput("n", "N:",
                                min = 10, max = 1000, value = 200, step = 10)
            )),
            column(8,
                   tableOutput("text")
            )
    )
   )

server.R

library(shiny)

function(input, output, session) {

    observed=reactiveValues(
            input=NULL
    )

    observe({    
            observed$input=input$n
           # observed$input=c(observed$input,input$n) # tried this but not working
    })

    output$text <- renderTable({
            observed$input
    })
    }
2

2 Answers

3
votes

If you add print(observed$input) in your observer, you will see that when you use observed$input=c(observed$input,input$n) you run into an infinite loop as the observe is reactive to observe$input and will run again as soon as you modify it.

To prevent this, you can use isolate:

observed$input=c(isolate(observed$input),input$n)

As in @Pork Chop 's answer, you can also use observeEvent to only observe input$n.

3
votes

Try this, you can use cbind or rbind depending on your needs

rm(list = ls())
library(shiny)

ui <- fluidPage(
  titlePanel("Observer demo"),
  fluidRow(
    column(4, wellPanel(
      sliderInput("n", "N:",
                  min = 10, max = 1000, value = 200, step = 10)
    )),
    column(8,
           tableOutput("text")
    )
  )
)

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

  observed=reactiveValues(
    input=NULL
  )

  observeEvent(input$n,{    
    observed$input <- cbind(observed$input,input$n)
  })

  output$text <- renderTable({
    print(observed$input)
    observed$input
  })
}

shinyApp(ui <- ui, server <- server)