2

I'm having trouble displaying a dataframe that depends on user input. I need to have users pick a number, do some very simple calculations based on those numbers, and display the resulting dataframe. Does this require reactive() or observe()? Or is my formatting just off?

Simple example that works if you remove the attempt to work with 'input$exp':

library(shiny)
shinyApp(
 ui = fluidPage(

   
   fluidRow(
     column(6, sliderInput("exp", label = h5("Change this"), min=2, max=5, value = 2)),
     
     column(12,
            tableOutput('table')
     )
   )
 ),
 server = function(input, output) {
   foo<-data.frame(matrix(ncol=8, nrow=1))
   colnames(foo)<-c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
   foo$a<-input$exp+2
   foo$b<-2
   foo$c<-3
   output$table <- renderTable(foo)
 }
)

1 Answer 1

2

Method 1:

library(shiny)
shinyApp(
  ui = fluidPage(        
    fluidRow(
      column(6, sliderInput("exp", label = h5("Change this"), min=2, max=5, value = 2)),       
      column(12,
             tableOutput('table')
      )
    )
  ),
  server = function(input, output) {
    output$table <- renderTable({
      foo<-data.frame(matrix(ncol=8, nrow=1))
      colnames(foo)<-c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
      foo$a<-input$exp+2
      foo$b<-2
      foo$c<-3
      return(foo)
    })
  }
) 

Method 2:

library(shiny)
shinyApp(
  ui = fluidPage(        
    fluidRow(
      column(6, sliderInput("exp", label = h5("Change this"), min=2, max=5, value = 2)),       
      column(12,
             tableOutput('table')
      )
    )
  ),
  server = function(input, output) {
    result <- eventReactive(input$exp, {
      foo<-data.frame(matrix(ncol=8, nrow=1))
      colnames(foo)<-c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
      foo$a<-input$exp+2
      foo$b<-2
      foo$c<-3
      return(foo)
    })  
    output$table <- renderTable({
      result()
    })
  }
)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that works. Any explanation why? If I just wanted to display 'input$exp+2' I can get that to work with renderText just fine without doing anything reactive. Why does that not require reactive but the dataframe does?
@GarretC I just updated the code. Maybe Method 1 is what you want which do not need reactive things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.