Garret C
Garret C

Reputation: 45

How to display a simple dataframe with input in R Shiny

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

Upvotes: 2

Views: 1874

Answers (1)

TichPi
TichPi

Reputation: 146

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

Upvotes: 2

Related Questions