首页 > 解决方案 > 在闪亮中使用“if”和“eventReactive”

问题描述

我对 Shiny 很陌生,我正在尝试构建一个使用 Web 服务检索数据的应用程序。在阅读了 Shiny 中的“反应性”之后,我认为“eventReactive”是最好的选择。它一直有效,直到没有“if”语句,但是一旦我使用“if”语句,它就停止了工作。下面是我正在尝试做的一个简化示例-

    library(shiny)


ui <- fluidPage(

   # Application title
   titlePanel("Get Data"),


   sidebarLayout(
      sidebarPanel(
        textInput("stationID", "Station ID(s)", value = ""), 
        radioButtons("DownloadType", "Download",
                     choices = c("Yes","No"),
                     selected = "No"),



        br(),
        radioButtons("DataType", "Data Availability",
                     choices = c("All","Selected"),
                     selected = "All"),
        actionButton("goButton","Go!")

      ),


      mainPanel(
        (tableOutput("results"))
      )
   ))


# Define server logic required to draw a histogram
server <- function(input, output) {
  data<-eventReactive(input$goButton, {
  if(input$DataType == "All" && input$DownloadType=="No"){
    employee <- c('X','Y','Z')
    salary <- c(100, 200, 300)
    df1<-data.frame(employee, salary)
    df1
  }

    if(input$DataType =="Selected" && input$DownloadType=="No"){
      employee <- c('A','B','C')
      salary <- c(100, 200, 300)
      df1<-data.frame(employee, salary) 

      employee2<-c('A','B','C')
      salary2 <- c(500, 600, 700)
      df2<-data.frame(employee2, salary2) 

      my_df<-merge(df1,df2,by.x="employee",by.y="employee2")
      my_df
    }
  })

  output$results<-renderTable({
    data()
  })
}

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

有人可以指出我正确的方向吗?当第一个“if”语句为真时,不会呈现任何表。但是,当第二个“if”语句为真时,它就起作用了。这个想法是单击应用程序上的“开始”按钮以根据输入组合呈现表格。预先感谢您的任何帮助。

标签: rshinyshiny-reactivity

解决方案


正如@Sada93 建议的那样,return明确添加返回值。

server <- function(input, output) {
    data<-eventReactive(input$goButton, {
        if(input$DataType == "All" && input$DownloadType=="No"){
            employee <- c('X','Y','Z')
            salary <- c(100, 200, 300)
            df1<-data.frame(employee, salary)
            return(df1) # add return
        }

        if(input$DataType =="Selected" && input$DownloadType=="No"){
            employee <- c('A','B','C')
            salary <- c(100, 200, 300)
            df1<-data.frame(employee, salary) 

            employee2<-c('A','B','C')
            salary2 <- c(500, 600, 700)
            df2<-data.frame(employee2, salary2) 

            my_df<-merge(df1,df2,by.x="employee",by.y="employee2")
            return(my_df) # add return
        }
    })

    output$results<-renderTable({
        data()
    })
}

推荐阅读