根据用户选择的值计算相关系数

问题描述 投票:0回答:1
作为更大的 Shiny 应用程序的一部分,我尝试按价格进行过滤(以钻石数据集为例)以创建反应式数据框。使用此数据框,我想将价格与用户选择的变量相关联。过滤器按预期工作。我在将选定的变量从过滤后的数据帧传递到 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)
    
dataframe shiny subset correlation reactive
1个回答
0
投票
试试这个

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)) })
    
© www.soinside.com 2019 - 2024. All rights reserved.