如果否则闪亮的陈述不能正常工作

时间:2019-12-17 03:50:54

标签: r shiny dt shiny-reactivity shinyapps

下面是我一直在研究的脚本。您会注意到,反应式语句table_data()是繁重的工作。运行应用程序时,您将看到所有三个过滤器均为空。它们假定为空,但是呈现的表应该生成一个表,该表表示该最终else if语句中的过滤输出:

res <- df %>% group_by(level1) %>% summarise(total=sum(sales)),因此在加载应用程序时,您应该首先看到的是:

enter image description here

但是不会产生这种情况。它产生一个空表。我正在努力了解我做错了什么。这是脚本:

level1 <- c('1','1','1','1','1','1','2','2','2','2','2','2','3','3','3','3','3','3')
level2 <- c('1A','1A','1B','1B','1C','1C','2A','2A','2B','2B','2C','2C','3A','3A','3B','3B','3C','3C')
level3 <- c('Jones','Smith','Johnson','James','Evans','Long','Roth','Goldberg','Ramos','Winston','Levin','Jackson','Fishman','Drake','Quinn','Lackey','Scott','McGuire')
sales <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18)

df <- cbind(level1,level2,level3,sales) %>% as.data.frame() %>% mutate(level1 = as.character(level1), level2 = as.character(level2), level3 = as.character(level3), sales = as.integer(sales))

ui <- fluidPage(
  fluidRow(
    column(8,
           width = 10, offset = 1,
           tags$h3("Select Area"),
           panel(
            selectInput('lev1', label = 'Level 1', c(unique(sort(df$level1))), multiple = TRUE),
            uiOutput("level2"),
            uiOutput("level3")
           ),
           DT::dataTableOutput(outputId = "test")
    )
  )
)

server <- function(input, output, session) {

  output$level2 <- renderUI({
    selectizeInput("lev2", "Level 2", multiple = TRUE, c(unique(sort(df$level2[df$level1 ==input$lev1]))))
  }) 

  output$level3 <- renderUI({
    selectizeInput("lev3", "Level 3", multiple = TRUE, c(unique(sort(df$level3[df$level2 ==input$lev2]))))
  })


table_data <- reactive({

  if(!is.null(input$lev1) & is.null(input$lev2) & is.null(input$lev3)) #When lev1 is not null, but the other two are
    res <- df %>% filter(level1 %in% input$lev1) %>% group_by(level1,level2) %>% summarise(total=sum(sales))
  else
    if(is.null(input$lev1) | !is.null(input$lev1) & !is.null(input$lev2) & is.null(input$lev3)) #When lev2 is not null, lev3 is null, and lev1 can be either/or
      res <- df %>% filter(level2 %in% input$lev2) %>% group_by(level2,level3) %>% summarise(total=sum(sales))
    else
      if(is.null(input$lev1) | !is.null(input$lev1) & is.null(input$lev2) | !is.null(input$lev2) & !is.null(input$lev3)) #When lev3 is not null, lev1 can be either/or, and lev2 can be either/or
        res <- df %>% filter(level3 %in% input$lev3) %>% group_by(level1,level2,level3) %>% summarise(total=sum(sales))
      else
        if(is.null(input$lev1) & is.null(input$lev2) & is.null(input$lev3)) #When lev1 is null, lev2 is null, and lev3 is null (THIS ONE IS NOT WORKING CORRECTLY)
      res <- df %>% group_by(level1) %>% summarise(total=sum(sales))

})

output$test <- DT::renderDataTable({
  table_data()
})

}

shinyApp(ui,server)

0 个答案:

没有答案