-->

dynamic filtering with input_select() using ggvis

2019-02-22 19:52发布

问题:

I'm using the built in "cocaine" database that comes with the ggvis package in R to visualize the potency counts of cocaine in each state. The R package dplyr was also used.

Here's the first six lines of the cocaine dataset:

 state potency weight month price
1    WA      77    217     1  5000
2    CT      51    248     1  4800
3    FL      68     43     1  3500
4    OH      69    123     1  3500
5    MS      75    118     1  3400
6    VA      73    127     1  3000

The goal was to use input_select()within the ggvis package to create a drop down menu where one could select various states and see a histogram of the potency counts for that state. We managed to do that with this code:

state <- as.vector(unique(cocaine$state))

cocaine %>%
          ggvis(~potency) %>%
            filter(state == eval(input_select(
            choices = state,
            selected = "NY",
            label = "State"))) %>%
          layer_histograms(binwidth = 2)

The question is why exactly we need the expression input_select() to be "evaluated" by eval(). A guess may be that becausefilter is a function from the dplyr package and thus is not communicating in the environment with ggvis; eval therefore initializes it within the ggvis environment. Perhaps someone can chime in with a concept that may help us visualize this?