没有活动的反应上下文ggvis就不允许操作

时间:2016-01-13 03:35:51

标签: r shiny ggvis

我正在尝试在闪亮的应用程序中创建一个简单的ggvis图。下拉列表有两个选项:mpv和mpc。两个选项都是两列数据帧,第一列为V1,第二列为V2。我希望能够选择mpc或mpv并将ggvis图添加到正确的更新中。我有以下ui和服务器代码:

# ui.R
shinyUI(fluidPage(
titlePanel("Barcelona"),
sidebarLayout(
sidebarPanel(
helpText("Display information about the selected variable"),
  selectInput("var", 
              label = "Choose a variable to display",
              choices = c("mpc", "mpv"),                 
              selected = "mpc")),

mainPanel(
  ggvisOutput("meanpc"))))) 

# server.R
shinyServer(
function(input, output) {
mpc <- mean.price.country
mpv <- mean.price.vintage

selection <- reactive({
  as.numeric(input$var)
})

  selection() %>%
    ggvis(~V1, ~V2) %>%
    layer_bars() %>%
    bind_shiny("meanpc")
})

我收到以下错误:

.getReactiveEnvironment()$ currentContext()中的错误:   没有活动的反应上下文,不允许操作。 (你试图做一些只能在反应式表达式或观察者内部完成的事情。)

知道错误是什么吗?谢谢。

1 个答案:

答案 0 :(得分:1)

您需要将其打包成observe语句,如下所示:

library(shiny)
library(ggvis)
library(dplyr)
# ui.R
u <- shinyUI(fluidPage(
  titlePanel("Barcelona"),
  sidebarLayout(
    sidebarPanel(
      helpText("Display information about the selected variable"),
      selectInput("var", 
                  label = "Choose a variable to display",
                  choices = c("mpc", "mpv"),                 
                  selected = "mpc")),
    mainPanel(
      ggvisOutput("meanpc"))))) 

# server.R
s <- shinyServer(
  function(input, output) {
    n <- 200
    set.seed(1234)
    wine <- data.frame( vintage=sample(c(2000:2015),n,replace=T), 
                        price=runif(n,10,150),
                        stock=runif(n,100,1500),
                        country=sample(c("Country-1","Country-2","Country-3"),n,replace=T) 
                        )
    mpc <- wine %>% group_by(country) %>% summarize( V1=mean(stock), V2=mean(price) )
    mpv <- wine %>% group_by(country) %>% summarize( V1=mean(stock), V2=mean(vintage) )

    selection <- reactive({ifelse (input$var=="mpc",return(mpc),return(mpv))})

    observe({
    selection() %>%
      ggvis(~V1, ~V2) %>%
      layer_bars() %>%
      bind_shiny("meanpc")
    })
  })
shinyApp(u,s)

产量:

enter image description here