4

Is it possible to display a plot only if a condition is met and to hide other plots if the condition is met?

I tried to work with conditionalPanel(). It works and shows the plot if the condition is met but it also shows the other two plots. I want to display coolPlot and coolPlot_2 only if the selected input is

"X1_P"   "X2_S"   "X3_W"   "X4_S"   "X5_P"   "X6_P"   "X7_P"  
"X8_S"   "X9_P"   "X10_P"  "X11_P"  "X12_I"

and coolPlot_3 has to be shown only if "X13_K" is selected and the other two panels should be hidden. I've used the following code.

    ui = fluidPage(
  titlePanel("Data Visualization"),
  sidebarLayout(
    sidebarPanel(
                 uiOutput("variableOutput"),
                 uiOutput("text1Output")
    ),
  mainPanel(
    conditionalPanel(
      condition = "input.variableOutput != 'X13_K'",
      plotOutput("coolPlot")),
    br(),
    br(),
    conditionalPanel(
      condition = "input.variableOutput != 'X13_K'",
      plotOutput("coolPlot_2")),
    conditionalPanel(
    condition = "input.variableOutput == 'X13_K'",
  plotOutput("coolPlot_3")),
  br(),
  br(),
  dataTableOutput(
    "coolTable"
      )
    )
  )
)

As has been suggested by Nice, I am also posting the server code.

server = function(input,output){
  output$variableOutput = renderUI({
    selectInput("VariableInput",
                "Variable auswählen",
                choices = colnames(training)[-1] ,
                selected = 2)


  })

  plot_data = reactive({frame = as.data.frame(cbind(training[,"flag"],
                                             training[,input$VariableInput]))

                        frame[,1] = as.logical(frame[,1])

                        return(frame)

  })

  mean_data = reactive({data.frame(flag = c("2","1"),
                                   data = c(weighted.mean(training[,input$VariableInput][training$flag==1],
                                             training$weight[training$flag==1]),
                                            weighted.mean(training[,input$VariableInput][training$flag==0],
                                             training$weight[training$flag==0])))
  })
    output$coolPlot_3 = renderPlot({

      if (is.null(input$VariableInput)) {
        return(NULL)
      } 

      numb_classes = length(levels(training[,input$VariableInput]))

      row_names = levels(training[,input$VariableInput])

      plot_data_2 = data.frame(klassen   = character(numb_classes),
                               index = numeric(numb_classes),
                               stringsAsFactors = FALSE)

      for (j in 1:numb_classes){

        count_class_non_goal = count(subset(training[,input$VariableInput],
                                            training[,input$VariableInput] == row_names[j] & training[,"flag"] == FALSE))

        count_all_non_goal = count(training[training$flag == FALSE,input$VariableInput])

        percent_non_goal = count_class_non_goal[,2]/(sum(count_all_non_goal[,2])/100)

        count_class_goal = count(subset(training[,input$VariableInput],
                                        training[,input$VariableInput] == row_names[j] & training[,"flag"] == TRUE))

        count_all_goal = count(training[training$flag == TRUE,input$VariableInput])

        percent_goal = count_class_goal[,2]/(sum(count_all_goal[,2])/100)

        plot_data_2[,1][j] = row_names[j]

        plot_data_2[,2][j] = round((percent_goal/percent_non_goal*100)-100,
                                   digits =2)
      }

      ggplot(data = plot_data_2) + 
        geom_bar(aes(y = index, 
                     x = klassen),
                 stat= "identity")+ 
        coord_flip()+
        theme(legend.position = "none",
              axis.title.x = element_text(size=15,
                                          face = "bold"),
              axis.text.y  = element_text(size=12),
              axis.text.x  = element_text(size=12),
              axis.title.y = element_text(size=15,
                                          face = "bold"))+
        labs(x = paste(input$VariableInput),
             y = "Index")
    })

    output$coolPlot = renderPlot({
    if (is.null(input$VariableInput)) {
      return(NULL)
    } 

    ggplot(data = plot_data()) + 
      geom_boxplot(aes(x=V1,
                       y=V2,
                       fill=V1),
                   outlier.shape = NA) + 
      guides(fill=FALSE)+
      scale_x_discrete(labels=c("Nicht-Ziel", "Ziel")) +
      coord_cartesian(ylim = c(min(plot_data()[,"V2"]),
                               quantile(plot_data()[,"V2"])[4] + IQR(plot_data()[,"V2"], 
                                                  na.rm = TRUE, type = 7)*1.9)) +
      stat_boxplot(aes(x=V1,
                       y=V2,
                       fill=V1),
                   geom ='errorbar') + 
      theme(axis.title.x = element_text(size=15,
                                        face = "bold"),
            axis.text.y  = element_text(size=12),
            axis.text.x  = element_text(size=12),
            axis.title.y = element_text(size=15,
                                        face = "bold"))+
      labs(x = paste(input$VariableInput),
           y = "Ausprägung der Variable")
  })

  output$coolPlot_2 = renderPlot({
    if (is.null(input$VariableInput)) {
      return(NULL)
    } 

    ggplot(data = plot_data(),
           aes(x=V2,
               fill=V1)) + geom_density(alpha=.3)+
      geom_vline(data=mean_data(), 
                 aes(colour=flag,
                     xintercept=data),
                linetype="dashed", size=1)+
      scale_fill_discrete(name = "Gruppen",
                          labels=c("Nicht-Ziel",
                                   "Ziel"))+
      theme(axis.title.x = element_text(size=15,
                                        face = "bold"),
            axis.text.y  = element_text(size=12),
            axis.text.x  = element_text(size=12),
            axis.title.y = element_text(size=15,
                                        face = "bold"))+
      labs(x = paste(input$VariableInput),
           y = "Density")


  })



  output$coolTable = renderDataTable({ 
    training
  })
}
stark
  • 2,246
  • 2
  • 23
  • 35
burton030
  • 405
  • 4
  • 8
  • 23
  • 1
    try `!=`, `!!` is not not so will be true if `output.variableOutput` is `X13_K` http://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript – NicE Feb 21 '16 at 23:01
  • This does not work. Doing coolPlot_3 is not displayed. Any other suggestions? – burton030 Feb 21 '16 at 23:15
  • 1
    Also it wouldn't work with `output.`, replace that with `input.id_of_whatever`. Maybe post your server.R code. – NicE Feb 21 '16 at 23:21
  • 1
    Have you tried replacing `input.variableOutput == 'X13_K'` with `input.VariableInput == 'X13_K'`, and respectively for the other two lines. – Alex Feb 24 '16 at 00:18
  • Thank you for the hint. I will try it when I am home. First I ve to work ;) – burton030 Feb 24 '16 at 08:33
  • Hey Alex, it worked fine. Thank you. Unfortunately I can't give you my bounty. Cause you made only a comment. – burton030 Feb 24 '16 at 20:07

1 Answers1

5

The prolbem is some missmatch in the nameing between server.r and ui.r

In server.r you declare

output$variableOutput = renderUI({
    selectInput("VariableInput",
                "Variable auswählen",
                choices = colnames(training)[-1] ,
                selected = 2)

which results in the following code

<select id="VariableInput" ...>
  <option value="X13_K"></option>
</select>

In the UI code you are then referencing

uiOutput("variableOutput"),

for outputing the control. This is right so far, as you defined the control as output$variableOutput.

However, things go wrong whne you write condition = "input.VariableOutput == 'X13_k'" This should refer to the id of the control which is defined as VariableInput in

 selectInput("VariableInput",
                    "Variable auswählen",
                    choices = colnames(training)[-1] ,
                    selected = 2)

so one fix would be to use as condition condition = "input.VariableInput == 'X13_k'"

However, my suggestsion would be to replace VariableInput and VariableOutput byVariableSelection` or something similar.

code with minimal fix for reference:

library(shiny)
library(ggplot2)
training=iris
names(training)[5] <- c("X13")

server = function(input,output){
  output$variableOutput = renderUI({
    selectInput("VariableInput",
                "Variable auswählen",
                choices = colnames(training)[-1] ,
                selected = 2)


  })

  plot_data = reactive({frame = as.data.frame(cbind(training[,1],
                                                    training[,input$VariableInput]))

  frame[,1] = as.logical(frame[,1])

  return(frame)

  })

  mean_data = reactive({data.frame(flag = c("2","1"),
                                   data = c(weighted.mean(training[,input$VariableInput][training$flag==1],
                                                          training$weight[training$flag==1]),
                                            weighted.mean(training[,input$VariableInput][training$flag==0],
                                                          training$weight[training$flag==0])))
  })
  output$coolPlot_3 = renderPlot({

    if (is.null(input$VariableInput)) {
      return(NULL)
    } 

    numb_classes = length(levels(training[,input$VariableInput]))

    row_names = levels(training[,input$VariableInput])

    plot_data_2 = data.frame(klassen   = character(numb_classes),
                             index = numeric(numb_classes),
                             stringsAsFactors = FALSE)

    for (j in 1:numb_classes){

      count_class_non_goal = count(subset(training[,input$VariableInput],
                                          training[,input$VariableInput] == row_names[j] & training[,"flag"] == FALSE))

      count_all_non_goal = count(training[training$flag == FALSE,input$VariableInput])

      percent_non_goal = count_class_non_goal[,2]/(sum(count_all_non_goal[,2])/100)

      count_class_goal = count(subset(training[,input$VariableInput],
                                      training[,input$VariableInput] == row_names[j] & training[,"flag"] == TRUE))

      count_all_goal = count(training[training$flag == TRUE,input$VariableInput])

      percent_goal = count_class_goal[,2]/(sum(count_all_goal[,2])/100)

      plot_data_2[,1][j] = row_names[j]

      plot_data_2[,2][j] = round((percent_goal/percent_non_goal*100)-100,
                                 digits =2)
    }

    ggplot(data = plot_data_2) + 
      geom_bar(aes(y = index, 
                   x = klassen),
               stat= "identity")+ 
      coord_flip()+
      theme(legend.position = "none",
            axis.title.x = element_text(size=15,
                                        face = "bold"),
            axis.text.y  = element_text(size=12),
            axis.text.x  = element_text(size=12),
            axis.title.y = element_text(size=15,
                                        face = "bold"))+
      labs(x = paste(input$VariableInput),
           y = "Index")
  })

  output$coolPlot = renderPlot({
    if (is.null(input$VariableInput)) {
      return(NULL)
    } 

    ggplot(data = plot_data()) + 
      geom_boxplot(aes(x=V1,
                       y=V2,
                       fill=V1),
                   outlier.shape = NA) + 
      guides(fill=FALSE)+
      scale_x_discrete(labels=c("Nicht-Ziel", "Ziel")) +
      coord_cartesian(ylim = c(min(plot_data()[,"V2"]),
                               quantile(plot_data()[,"V2"])[4] + IQR(plot_data()[,"V2"], 
                                                                     na.rm = TRUE, type = 7)*1.9)) +
      stat_boxplot(aes(x=V1,
                       y=V2,
                       fill=V1),
                   geom ='errorbar') + 
      theme(axis.title.x = element_text(size=15,
                                        face = "bold"),
            axis.text.y  = element_text(size=12),
            axis.text.x  = element_text(size=12),
            axis.title.y = element_text(size=15,
                                        face = "bold"))+
      labs(x = paste(input$VariableInput),
           y = "Ausprägung der Variable")
  })

  output$coolPlot_2 = renderPlot({
    if (is.null(input$VariableInput)) {
      return(NULL)
    } 

    ggplot(data = plot_data(),
           aes(x=V2,
               fill=V1)) + geom_density(alpha=.3)+
      geom_vline(data=mean_data(), 
                 aes(colour=flag,
                     xintercept=data),
                 linetype="dashed", size=1)+
      scale_fill_discrete(name = "Gruppen",
                          labels=c("Nicht-Ziel",
                                   "Ziel"))+
      theme(axis.title.x = element_text(size=15,
                                        face = "bold"),
            axis.text.y  = element_text(size=12),
            axis.text.x  = element_text(size=12),
            axis.title.y = element_text(size=15,
                                        face = "bold"))+
      labs(x = paste(input$VariableInput),
           y = "Density")


  })



  output$coolTable = renderDataTable({ 
    training
  })
}

library(shiny)
ui = fluidPage(
  titlePanel("Data Visualization"),
  sidebarLayout(
    sidebarPanel(
      uiOutput("variableOutput"),
      uiOutput("text1Output")
    ),
    mainPanel(
      conditionalPanel(
        "input.VariableInput != 'X13'",
        plotOutput("coolPlot")),
     # textInput("bla","blub",input.variableOutput),
      br(),
      br(),
      conditionalPanel(
        condition = "input.VariableInput != 'X13'",
        plotOutput("coolPlot_2")),
      conditionalPanel(
        condition = "input.VariableInput == 'X13'",
        plotOutput("coolPlot_3")),
      br(),
      br(),
      dataTableOutput(
        "coolTable"
      )
    )
  )
)
CAFEBABE
  • 3,983
  • 1
  • 19
  • 38