r shinyapp:使用 numericInput 更改数据框

r shinyapp: Change dataframe using numericInput

我有以下闪亮的应用程序,它由一个数字输入和两个 ggplot-graphics 作为输出组成。

library(shiny)

n <- 100
dat <- data.frame(var1 = round(rnorm(n, 50, 10),0),
                  var2 = sample(c("A", "B"), n, replace = TRUE))

# USER INTERFACE
ui <- fluidPage(

    titlePanel("My Sample App"),

    sidebarLayout(
        sidebarPanel(
            numericInput("n", "Number of cases", value=100)
        ),


        mainPanel(
           plotOutput("boxplot"),
           plotOutput("distribution")
        )
    )
)

# SERVER
server <- function(input, output) {

    output$boxplot <- renderPlot({
        ggplot(data = dat, aes(x = var2, y = var1)) + geom_boxplot() + ggtitle("Boxplot")
    })
    output$distribution <- renderPlot({
        ggplot(data = dat, aes(var1)) + geom_histogram() + ggtitle("Histogram")
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

我一直在尝试用 n = input$n 替换 n = 10。但是它没有用,我不确定我必须在哪里定义 data.frame (在服务器函数内?)。有人可以帮忙吗?

input$n 是一个反应变量,只能在 反应上下文 中使用。您只能在 server 函数中定义反应上下文,例如使用 reactive。看看 here 的解释。

library(shiny)
library(ggplot2)


# USER INTERFACE
ui <- fluidPage(
  
  titlePanel("My Sample App"),
  
  sidebarLayout(
    sidebarPanel(
      numericInput("n", "Number of cases", value=100)
    ),
    
    
    mainPanel(
      plotOutput("boxplot"),
      plotOutput("distribution")
    )
  )
)

# SERVER
server <- function(input, output) {
  
  dat <- reactive({
    data.frame(var1 = round(rnorm(input$n, 50, 10),0),
               var2 = sample(c("A", "B"), input$n, replace = TRUE))
  })
  
  output$boxplot <- renderPlot({
    ggplot(data = dat(), aes(x = var2, y = var1)) + geom_boxplot() + ggtitle("Boxplot")
  })
  output$distribution <- renderPlot({
    ggplot(data = dat(), aes(var1)) + geom_histogram() + ggtitle("Histogram")
  })
}

# Run the application 
shinyApp(ui = ui, server = server)