As part of a larger Shiny app, I'm trying to filter (using the diamonds dataset as an example) by price to create a reactive data frame. Using this data frame, I would like to correlate price with a user-selected variable. The filter works as expected. I'm having trouble passing the selected variables from the filtered data frame to cor().
library(shiny)
library(tidyverse)
num_vars <- c("", "carat", "depth", "table", "price", "x", "y", "z")
ui <- fluidPage(
sliderInput("price",
"Price range",
min = 300,
max = 20000,
value = c(10000, 12000)
),
selectInput("var", "Variable to plot",
choices = c("", "carat", "depth", "table", "x", "y", "z")
),
textOutput("correlation")
)
server <- function(input, output, session) {
df <- reactive(diamonds %>% filter(price > .env$input$price[1] &
price < .env$input$price[2]))
output$correlation <- renderText({
df_local <- df()
x <- df_local[[input$price]]
y <- df_local[[input$var]]
paste0(cor(x, y))
})
}
shinyApp(ui = ui, server = server)
Try this
output$correlation <- renderText({
req(input$var,input$price,df())
df_local <- df()
x <- df_local["price"]
y <- df_local[[input$var]]
paste0(cor(x, y))
})