Home > OS >  R Shiny renderPlotly with multiple conditions
R Shiny renderPlotly with multiple conditions

Time:06-24

I am making a Shiny app that allows the user to:

  1. Upload a CSV file
  2. Output summary
  3. Select columns/variables to plot

Based on the input y selected column I want the app to filter the data. For example, let's the say the user selects the column/variable tmean. Now, the data has a variable column which has tmean, TMax and TMin corresponding to the tmean, TMax and TMin values. So, the app will then filter just the tmean data by setting filter in variable column to `tmean.

Since, I have three temperature variables, I tried using conditional statements for filtering the data. However, the conditional statements are returning an error:

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

How can I fix this?

Sample Data:

structure(list(tmean = c(19.02, 15.14, 20.17, 20.37, 24.7, 26.03, 
28.19, 28.89, 28.36, 27.71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0), TMax = c(0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 28.07, 28.53, 28.92, 28.22, 26.91, 28.83, 28.13, 25.33, 
24.05, 29.98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), TMin = c(0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21.75, 
21.76, 19.97, 19.48, 21.31, 21.76, 21.55, 21.54, 21.72, 21.49
), year = c(1980L, 1980L, 1980L, 1980L, 1980L, 1981L, 1981L, 
1981L, 1981L, 1981L, 1980L, 1980L, 1980L, 1980L, 1980L, 1981L, 
1981L, 1981L, 1981L, 1981L, 1980L, 1980L, 1980L, 1980L, 1981L, 
1981L, 1981L, 1981L, 1981L, 1981L), month = c(1L, 1L, 1L, 2L, 
2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 
1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L), variable = c("tmean", 
"tmean", "tmean", "tmean", "tmean", "tmean", "tmean", "tmean", 
"tmean", "tmean", "TMax", "TMax", "TMax", "TMax", "TMax", "TMax", 
"TMax", "TMax", "TMax", "TMax", "TMin", "TMin", "TMin", "TMin", 
"TMin", "TMin", "TMin", "TMin", "TMin", "TMin")), class = "data.frame", row.names = c(NA, 
-30L))

enter image description here

Selection Criteria (y-axis variable can also be TMax or TMin):

enter image description here

Code:

library(shiny)
library(tidyverse)
library(plotly)
# Define UI for application that draws an interactive ggplot
options(shiny.maxRequestSize=1024*1024^2)
ui =   navbarPage("Data",
                  tabPanel("Uploading Files",
                           sidebarLayout(
                             sidebarPanel(
                               radioButtons(
                                 "File_Type",
                                 label = "Choose File type",
                                 choices = list(".csv/txt" = 1, ".xlsx" = 2),
                                 selected = 1,
                                 inline = TRUE
                               ),
                               
                               fileInput('file2', 'Upload Your Data',
                                         accept = c(
                                           'text/csv',
                                           'text/comma-separated-values,text/plain',
                                           '.csv',
                                           '.xlsx'
                                         ))),
                             mainPanel(
                               verbatimTextOutput("summary")
                             )
                             
                           )),
                  
                  tabPanel("Data Plots",
                           sidebarLayout(sidebarPanel(
                             selectInput("x", label = "Select x-axis Variable:",
                                         choices = NULL),
                             selectInput("y", label = "Select y-axis Variable: ",
                                         choices = NULL),
                             selectInput("color", label =  "Select Grouping variable (optional): ",
                                         choices = NULL)),
                             mainPanel(
                               plotlyOutput("TSM")
                             )))
)


# Tell the server how to assemble inputs into outputs
server = function(input, output, session) {
  # Code for uploading an MS-Excel file for plotting
  # Get the uploaded file
  myData = reactive({
    req(input$file2)
    inFile = input$file2
    if (is.null(inFile)) return(NULL)
    data = read.csv(inFile$datapath, header = TRUE)
    data
  })
  
  observe({
    data = req(myData())
    updateSelectInput(session, 'x', choices = names(data), select=names(data)[2])
    updateSelectInput(session, 'y', choices = names(data), select=names(data)[1])
    updateSelectInput(session, 'color', choices = names(data), select=names(data)[3])
  })
  
  output$summary = renderPrint({
    summary(myData())
  })

    df2 = reactive({
    req(myData(),input$x, input$y, input$color)
    myData() %>%
      if (input$y == "tmean") {
        myData() %>%
          filter(variable == "tmean") }

    else if (input$y == "TMin") {
      myData() %>%
        filter(variable == "TMin") }

    else if (input$y == "TMax") {
      myData() %>%
        filter(variable == "TMax") } %>%            
        group_by(.data[[input$x]], .data[[input$y]]) %>%
        dplyr::summarise(AvgTemp = mean(.data[[input$y]]))
  })
  
  #TSM
  output$TSM =  renderPlotly({
    req(df2(), input$x, input$y, input$color)

    df2() %>%
     ggplot(aes(x = .data[[input$x]], y = AvgTemp, color = as.factor(.data[[input$color]])))  
     labs(color = "Legend")  
     geom_line()  
     ggtitle("Timeseries Plot By Month")

  })
  
}

# Run the application
shinyApp(ui = ui, server = server)

CodePudding user response:

Try this

library(shiny)
library(tidyverse)
library(plotly)
# Define UI for application that draws an interactive ggplot
options(shiny.maxRequestSize=1024*1024^2)
ui =   navbarPage("Data",
                  tabPanel("Uploading Files",
                           sidebarLayout(
                             sidebarPanel(
                               radioButtons(
                                 "File_Type",
                                 label = "Choose File type",
                                 choices = list(".csv/txt" = 1, ".xlsx" = 2),
                                 selected = 1,
                                 inline = TRUE
                               ),
                               
                               fileInput('file2', 'Upload Your Data',
                                         accept = c(
                                           'text/csv',
                                           'text/comma-separated-values,text/plain',
                                           '.csv',
                                           '.xlsx'
                                         ))),
                             mainPanel(
                               verbatimTextOutput("summary")
                             )
                             
                           )),
                  
                  tabPanel("Data Plots",
                           sidebarLayout(sidebarPanel(
                             selectInput("x", label = "Select x-axis Variable:",
                                         choices = NULL),
                             selectInput("y", label = "Select y-axis Variable: ",
                                         choices = NULL),
                             selectInput("color", label =  "Select Grouping variable (optional): ",
                                         choices = NULL)),
                             mainPanel(
                               plotlyOutput("TSM", height = 500)
                             )))
)


# Tell the server how to assemble inputs into outputs
server = function(input, output, session) {
  # Code for uploading an MS-Excel file for plotting
  # Get the uploaded file
  myData = reactive({
    req(input$file2)
    inFile = input$file2
    if (is.null(inFile)) return(NULL)
    data = read.csv(inFile$datapath, header = TRUE)
    data
  })
  
  observe({
    data = req(myData())
    updateSelectInput(session, 'x', choices = names(data), select=names(data)[3])
    updateSelectInput(session, 'y', choices = names(data), select=names(data)[1])
    updateSelectInput(session, 'color', choices = names(data), select=names(data)[4])
  })
  
  output$summary = renderPrint({
    req(myData())
    summary(myData())
  })
  
  df2 = reactive({
    req(myData(),input$x, input$y)
    myData() %>% dplyr::filter(Variable %in% input$y)  %>%   
      group_by(.data[[input$x]], .data[[input$y]], .data[[input$color]]) %>%
      dplyr::mutate(AvgTemp = mean(.data[[input$y]]))
  })
  observe({print(df2())})
  #TSM
  output$TSM =  renderPlotly({
    req(df2(), input$x, input$y, input$color)
    
    df2() %>%
      ggplot(aes(x = .data[[input$x]], y = AvgTemp, color = as.factor(.data[[input$color]]) ))   
      labs(color = "Legend")  
      geom_line()  
      ggtitle("Timeseries Plot By Month")
    
  })
  
}

# Run the application
shinyApp(ui = ui, server = server)

output

  • Related