0

我有一个 flexdashboard 文档runtime: shiny我在这里发布了应用程序https://arie.shinyapps.io/reproducible_example/并嵌入了代码,但也想将代码放在下面,以防应用程序超出其在 shinyapps.io 上的分配使用量):

--- title: "Example" runtime: shiny output: flexdashboard::flex_dashboard: source_code: embed ---

给定以下示例数据集:

```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)

df <- tibble(name = c("peter", "paul", "mary"), 
         value = c(1:3))
```

我希望能够从以下用户界面中进行多项选择:

Column {data-width=250, .sidebar}
-----------------------------------------------------------------------

```{r}

# creates interface
selectInput("name_input", label = "Name", choices = df$name,
        selected = NULL, multiple = TRUE, selectize = TRUE)

```

并对选择​​进行 ggplot “反应”。所以我做了一个反应数据集:

```{r}
# reactive data
df_reactive <- reactive(df[df$name == input$name_input,])

```

并创建以下图:

Column {data-width=750}
-----------------------------------------------------------------------

### Chart B

```{r}
renderPlot(
 ggplot(df_reactive(), aes(x = input$name_input, y = value) ) +
  geom_col()
 )
```

现在,当 IRun Document和 select first peter、 thenpaul和 thenmary时,情节的反应完全符合预期:每次添加名称时都会添加一个条形图。例如,当我首先选择paul然后peter抛出错误时,就会出现问题Aesthetics must be either length 1 or the same as the data (2): x, y

在静态图表的上下文中,该错误对我来说是有意义的,但我对为什么选择名称的顺序很重要以及如何解决它感到困惑。

4

1 回答 1

1

问题在于:

df_reactive <- reactive(df[df$name == input$name_input,])

如果length(input$name_input)is < 3,您将尝试比较两个不同长度的数组。R 会抛出一个错误,它也不是你真正想要执行的测试。如我所见,您想测试每个元素df$name是否包含在input$name_input. 幸运的是,在 R 中有一个快捷方式,因此您不必使用 for 循环或sapply(),...

就像我在评论中写的:df_reactive <- reactive(df[df$name %in% input$name_input,])也可以。

有关符号的更多详细信息,我将参考现有答案,因为那时答案将变得更加重复。==和之间的区别在%in%这里解释: `%in%` VS `==` 之间的区别

于 2017-05-26T19:03:03.417 回答