如何在我的ggvis代码中使用条件?

时间:2016-01-14 09:33:08

标签: r shiny conditional-statements ggvis

我有一个我想绘制的不同列的数据框,但是我在Shiny中创建了一个复选框来指示我想要绘制哪些。

UI.R

tabPanel('Data Insights',
           mainPanel(
                      ggvisOutput("plot4"),
                      fluidRow(
                               checkboxGroupInput('investcheck', 'Investment', 
                                              choices = c('OOH', 'PRINT', 'TV', 'DIGITAL'), 
                                              selected=c('TV')))             
           )
  )

SERVER.R

reactive({
    if(is.element('PRINT', input$investcheck)) {oprint=1} else {oprint=0}
    if(is.element('OOH', input$investcheck)) {oooh=1} else {oooh=0}
    if(is.element('TV', input$investcheck)) {otv=1} else {otv=0}
    if(is.element('DIGITAL', input$investcheck)) {odigital=1} else {odigital=0}

    plt <- df_sales %>% ggvis(~sales) %>%
    if(oprint==1) {
      plt <- plt %>%
      layer_points(data = df_sales, x = ~sales, y = ~PRINT_Investment, fill:='3498DB')
    } else{
      plt <- plt %>%
        layer_points(data = df_sales, x = ~sales, y = ~PRINT_Investment, fill:='3498DB')
    }
    plt

  }) %>% bind_shiny("plot4")

但我总是有错误:

Warning in if (.) oprint == 1 else { :
  the condition has length > 1 and only the first element will be used
Error in if (.) oprint == 1 else { : 
  argument is not interpretable as logical

1 个答案:

答案 0 :(得分:1)

我终于纠正了!这是一个额外的'%&gt;%',我改变了我的代码:

SERVER.R

  reactive({


    plt <- df_sales %>% ggvis(~sales)
    if('PRINT' %in% input$investcheck) {
      plt <- plt %>%
      layer_points(data = df_sales, x = ~sales, y = ~PRINT_Investment, fill:='3498DB')
    }
    if('TV' %in% input$investcheck) {
      plt <- plt %>%
        layer_points(data = df_sales, x = ~sales, y = ~TV_Investment, fill:='1ABC9C')
    }
    if('OOH' %in% input$investcheck) {
      plt <- plt %>%
        layer_points(data = df_sales, x = ~sales, y = ~OOH_Investment, fill:='F39C12')
    }
    if('DIGITAL' %in% input$investcheck) {
      plt <- plt %>%
        layer_points(data = df_sales, x = ~sales, y = ~DIGITAL_Investment, fill:='E74C3C')
    }

    plt

  }) %>% bind_shiny("plot4")