Search code examples
rshiny-servershiny

How to link ui dropdown menu choice to server output in shiny


Super new to Shiny. I am trying to develop an app that calculates different correlation/agreement coefficients as well as display graphs.

I am lost on how to link my test choices from the drop down menu. At this point I can only conduct correlation tests using cor with three choices - Spearman, Pearson, and Kendall. I want to incorporate a Cohen's kappa test (using package fmsb, and the command Kappa.test(selectedData())). I tried if else statements to incorporate Kappa inside the renderPrint command but I keep getting error messages.

At this stage I am less concerned about what appropriate variables to use for each test. I post my code below.

Thanks

library(shiny)

# Loading package for Kappa test
library(fmsb)

# Generating simulated data
   dat <- as.data.frame(dat)

UI.R

ui <- fluidPage(
  pageWithSidebar(
    headerPanel('Correlation coefficient and scatter plots'),
    sidebarPanel(
      selectInput('xcol', 'X Variable', names(dat)),
      selectInput('ycol', 'Y Variable', names(dat),
                  selected=names(dat)[[2]]),
      selectInput(inputId = "measure", label = "Choose the correlation measure that you want to use",
                  choices = c("Spearman correlation" = "spearman",
                              "Pearson correlation" = "pearson",
                              "Kendall's W" = "kendall",
                              "Cohen's kappa" = "kappa"))
    ),
    mainPanel(
      plotOutput('plot1'),
      verbatimTextOutput('stats')
    )
  )
)

Server.R

server <- function(input, output){

  # Combine the selected variables into a new data frame
  selectedData <- reactive({
    dat[, c(input$xcol, input$ycol)]
  })

  output$plot1 <- renderPlot({
    plot(selectedData(),pch = 20, cex = 3, col = "red")
  })

  output$stats <- renderPrint({

      round(cor(selectedData(), method = input$measure), 3)
      })
}

shinyApp(ui = ui, server = server)

Solution

  • You can just throw in your condition inside the renderPrint function:

    output$stats <- renderPrint({
        measure <- input$measure
        mydat <- selectedData()
        if(measure == "kappa") {
          Kappa.test(mydat[,1], mydat[,2])
        } else {
          round(cor(mydat, method = measure), 3)
        }
    })