neversaint neversaint -4 years ago 79
R Question

How to make dplyr::filter from vector work in Shiny app

I have the following Rmarkdown:

---
title: "Untitled"
runtime: shiny
output:
flexdashboard::flex_dashboard:
theme: bootstrap
orientation: columns
vertical_layout: scroll
---

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

Column {data-width=650}
-----------------------------------------------------------------------

```{r}

sidebarPanel( textInput("flowers", "flower name(s)", "virginica, setosa") )
mainPanel(
renderPrint({
flower_list <- unlist(lapply(strsplit(input$flowers, ",")[[1]], tolower))
dat <- iris %>% filter(Species %in% flower_list)
unique(dat$Species)
})



)

```


Basically what it does is to take input from user and return list of
names after filtering. But it seems that it doesn't work:

enter image description here

For example the main panel should return two values
virginia setosa
.
What's the right way to do it?

In console it works fine:





library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
dat <- iris %>%
filter(Species %in% c("virginica","setosa"))
unique(dat$Species)
#> [1] setosa virginica
#> Levels: setosa versicolor virginica

Answer Source

That is because of the space between virginia and setosa in sidebarPanel( textInput("flowers", "flower name(s)", "virginica, setosa") ). You can either remove the space or remove the white spaces by modifying your code with something like this:

flower_list <- trimws(unlist(lapply(strsplit(input$flowers, ",")[[1]], tolower)))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download