代码之家  ›  专栏  ›  技术社区  ›  Eric Green

当数据集中没有符合输入的观测值时,过滤闪亮的selectizeInput并显示空白图

  •  0
  • Eric Green  · 技术社区  · 7 年前

    在我的flexdashboard闪亮应用程序中,我使用 selectizeInput() 有三个选项:“英语”、“西班牙语”和“其他”。在我的玩具数据集中,没有观察到的变量 lang 取“其他”值。因此,当 只有 在输入栏中选择“其他”,R返回一个计算错误:

    缺少需要TRUE/FALSE的值。

    这是由“第1页”一节中的以下管道引起的:

    filter(if(is.null(input$foo)) (new==1) else (lang %in% input$foo)) %>%

    当数据集中没有观测到输入值时,显示空白图的正确方法是什么?

    ---
    title: "test"
    output: 
      flexdashboard::flex_dashboard:
        theme: bootstrap
    runtime: shiny
    ---
    
    ```{r setup, include=FALSE}
      library(flexdashboard)
      library(tidyverse)
      library(tibbletime)
      library(dygraphs)
      library(magrittr)
      library(xts)
    ```
    
    ```{r global, include=FALSE}
    # generate data
      set.seed(1)
      dat <- data.frame(date = seq(as.Date("2018-01-01"), 
                                   as.Date("2018-06-30"), 
                                   "days"),
                        sex = sample(c("male", "female"), 181, replace=TRUE),
                        lang = sample(c("english", "spanish"), 181, replace=TRUE),
                        age = sample(20:35, 181, replace=TRUE))
      dat <- sample_n(dat, 80)
    
    ```
    
    Sidebar {.sidebar}
    =====================================
    
    ```{r}
    selectizeInput(
      'foo', label = NULL, 
      choices = c("english", "spanish", "other"),
      multiple = TRUE
    )
    ```
    
    Page 1
    =====================================
    
    ```{r}
    # all
      totals <- reactive({
      dat %>%
        mutate(new = 1) %>%
        arrange(date) %>%
        filter(if(is.null(input$foo)) (new==1) else (lang %in% input$foo)) %>%
      # time series analysis
      tibbletime::as_tbl_time(index = date) %>% # convert to tibble time object
        select(date, new) %>%
        tibbletime::collapse_by("1 week", side = "start", clean = TRUE) %>%
        group_by(date) %>%
        mutate(total = sum(new, na.rm = TRUE)) %>%
        distinct(date, .keep_all = TRUE) %>%
        ungroup() %>%
        # expand matrix to include weeks without data
        complete(
          date = seq(date[1], date[length(date)], by = "1 week"),
          fill = list(total = 0)
        )
      })
    
    # convert to xts
      totals_ <- reactive({
        totals <- totals()
        xts(totals, order.by = totals$date)
      })
    
    # plot
      renderDygraph({
    
      totals_ <- totals_()
      dygraph(totals_[, "total"]) %>%
        dyRangeSelector() %>%
        dyOptions(useDataTimezone = FALSE,
                  stepPlot = TRUE,
                  drawGrid = FALSE,
                  fillGraph = TRUE) 
      })
    ```
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   divibisan    7 年前

    一种方法是使用 shiny::req 函数在运行代码块之前检查需求。

    req(dat$lang %in% input$foo)
    

    到你的头顶 totals <- reactive({ 表达式,则它将检查 input$foo dat$lang

    推荐文章