shiny + ggvis: reactive using ggvis “tilde” or “~”

强颜欢笑 提交于 2019-12-11 19:44:31

问题


All I want is an efficient way to set the ggvis fill property in server.R according to the InputSelect box in ui.R. Since the fill property syntax needs a "tilde" or "~" I was unable to come with a solution.

The ui.R and server.R below are just one of my solutions attempts: my switch statement below is wrong since I get a "Error in switch(select, mpg = { : EXPR must be a length 1 vector". Don't hesitate to propose something completely different.

Thanks in advance for your support !

ui.R

shinyUI(fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("select", label = h3("Select box"), 
                  choices = list("mpg" = "mpg", "hp" = "hp", "cyl" = "cyl"), 
                  selected = "mpg")
    ),
    mainPanel(
      uiOutput("ggvis_ui"),
      ggvisOutput("ggvis")
    )
  )
))

server.R

data(mtcars)

shinyServer(
  function(input, output) {
    select <- reactive({as.character(input$select)})
      data <- switch(select, 
                     mpg = {mtcars %>% 
                       ggvis(~mpg, ~wt, 
                             fill = ~mpg) %>% 
                       layer_points() %>%
                       bind_shiny("ggvis", "ggvis_ui")},
                     hp = {mtcars %>% 
                       ggvis(~mpg, ~wt, 
                             fill = ~hp) %>% 
                       layer_points() %>%
                       bind_shiny("ggvis", "ggvis_ui")},
                     cyl = {mtcars %>% 
                       ggvis(~mpg, ~wt, 
                             fill = ~cyl) %>% 
                       layer_points() %>%
                       bind_shiny("ggvis", "ggvis_ui")}
      )    
  }
)

回答1:


You can try to running the select expression using select(), and wrap your switch in an observer to plot the data reactively:

The server.R would be:

shinyServer(
  function(input, output) {
    select <- reactive({as.character(input$select)})
    observe({
    data <- switch(select(), 
                   mpg = {mtcars %>% 
                            ggvis(~mpg, ~wt, 
                                  fill = ~mpg) %>% 
                            layer_points() %>%
                            bind_shiny("ggvis", "ggvis_ui")},
                   hp = {mtcars %>% 
                           ggvis(~mpg, ~wt, 
                                 fill = ~hp) %>% 
                           layer_points() %>%
                           bind_shiny("ggvis", "ggvis_ui")},
                   cyl = {mtcars %>% 
                            ggvis(~mpg, ~wt, 
                                  fill = ~cyl) %>% 
                            layer_points() %>%
                            bind_shiny("ggvis", "ggvis_ui")}
    ) 
    data
    })
  }
)


来源:https://stackoverflow.com/questions/28876873/shiny-ggvis-reactive-using-ggvis-tilde-or

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!