在闪亮的selectizeInput上进行过滤,并在数据集中没有符合输入条件的观测值时显示空白图

时间:2018-09-13 17:04:56

标签: r shiny

在我的flexdashboard闪亮应用程序中,我使用的selectizeInput()具有三个选项:“英语”,“西班牙语”和“其他”。在我的玩具数据集中,没有观察到变量lang带有值“ other”。因此,在输入栏中选择“其他”时,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) 
  })
```

0 个答案:

没有答案