如何在 R Shiny 中显示带有输入的简单数据框

How to display a simple dataframe with input in R Shiny

我在显示依赖于用户输入的数据框时遇到问题。我需要让用户选择一个数字,根据这些数字进行一些非常简单的计算,然后显示结果数据框。这是否需要 reactive() 或 observe()?还是我的格式刚刚关闭?

一个简单的例子,如果你删除尝试使用 '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)
 }
)

方法一:

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

方法二:

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