如何在本地的数据框中包含selectInput()中的选项而不在R内存中预先重新加载它

时间:2018-05-20 15:57:50

标签: r ggplot2 shiny

除非我从ShinyApp预加载Data,否则我无法运行server

如果我在运行App之前没有阅读Data,则会抛出错误:

> runApp('example.R')
Error in lapply(obj, function(val) { : object 'Data' not found

如果我选择所有代码并运行它,它可以正常工作。

有人可以解释为什么以及如何解决它。

这是我的代码:

library(shiny)
library(ggplot2)
ui <- fluidPage(
  column(12,selectInput("id_1","Choose the x axis",Data$Species)),
  column(12,plotOutput("plot"))
)

server <- function(input, output, session) {
  Data=iris
  output$plot=renderPlot(
    ggplot(Data[Data$Species==input$id_1,],aes(x=Sepal.Length,y=Petal.Length))+geom_point()+
      labs(x="Sepal Length",y="Petal Length",title=paste0("Sepal Length vs Petal Length for ",input$id_1))+
      theme(panel.background=element_blank())
  )
  }
shinyApp(ui = ui, server = server)
runApp('example.R')

1 个答案:

答案 0 :(得分:1)

您必须将selectInput放在renderUI函数内的server函数中,因为它必须对所选输入作出反应。这在Ui中不起作用。并且您必须在renderplot函数中包含req(input$id_1),因此它会等到选择了某些内容。

library(shiny)
library(ggplot2)
ui <- fluidPage(
  column(6,uiOutput("uimod")),
  column(6,plotOutput("plot"))
)

server <- function(input, output, session) {
  Data=iris

  output$uimod <- renderUI({
    selectInput("id_1","Choose the x axis",Data$Species)
  })
  output$plot=renderPlot({
    req(input$id_1)
    ggplot(Data[Data$Species==input$id_1,],aes(x=Sepal.Length,y=Petal.Length))+
      geom_point()+
      labs(x="Sepal Length",y="Petal Length",
           title=paste0("Sepal Length vs Petal Length for ",input$id_1))+
      theme(panel.background=element_blank())
  })
}
shinyApp(ui = ui, server = server)

为什么你需要runApp('example.R')?哪个例子.R应该在那里运行? 如果你想启动shinyApp,函数shinyApp(ui, server)就可以了。如果你选择并运行你在这里显示的所有代码,R将永远不会进入runApp()行,因为它将打开闪亮的App 1行,因此它不会执行最后一行。