动态变量选择在shinyApp中的回归 [英] Regression in shinyApp with dynamic variable selection
本文介绍了动态变量选择在shinyApp中的回归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望对FEATURE_A执行线性回归,并希望用户动态选择另一个变量。我还想显示有关我的整体预测模型拟合调整后的R2、每个模型估计的参数系数和系数p值的统计信息。
下面是我能想到的。不用说,这是行不通的。我一直在努力解决这个问题,任何帮助我都将不胜感激。
library(shiny)
library(ggplot2)
library(dplyr)
library(purrr)
Feature_A <- c(1, 2,1, 4,2)
Feature_B <- c(4,5,6,6,6)
Feature_C <- c(22,4,3,1,5)
df<- data.frame(Feature_A ,Feature_B ,Feature_C)
# Define UI for application
ui= fluidPage(
# Header or Title Panel
titlePanel(title = h4("Regression")),
sidebarLayout(
# Sidebar panel
sidebarPanel(
selectInput('ip', 'Select an Explanatory Variable', names(df)),
actionButton(inputId = "btn1",label="Regression Plot"),
actionButton(inputId = "btn2",label="Show Stats")),
# Main Panel
mainPanel("main panel", regOutput("regplot"),
verbatimTextOutput("summary"))
))
server = function(input, output,session) {
#code for regression
lm_fit <- lm(Feature_A ~ input$ip, data=df)
summary_stats <- eventReactive(input$btn2,{summary(lm_fit)
})
regression_plot<- eventReactive(input$btn1,{ggplot(data = df, aes(x = input$ip, y = Feature_A)) +
geom_point(color='blue') +
geom_smooth(method = "lm", se = FALSE)
})
#end of regression code
output$regplot <- renderPlot({
regression_plot()
})
output$summary <- renderPrint({
summary_stats()
})
}
shinyApp(ui,server)
推荐答案
这里有几处错误:
regOutput
不是现有命令,您需要plotOutput
。lm_fit <- lm(Feature_A ~ input$ip, data=df)
应处于被动状态,因为它使用input$ip
。这意味着您需要lm_fit()
获取结果,而不是lm_fit
。- 另外,
input$ip
是字符,lm()
需要formula
。因此,您需要将整个公式放在as.formula
中。
现在应该可以用了,这个情节有点奇怪,但我想这是因为您的简化示例:
library(shiny)
library(ggplot2)
library(dplyr)
library(purrr)
Feature_A <- c(1, 2,1, 4,2)
Feature_B <- c(4,5,6,6,6)
Feature_C <- c(22,4,3,1,5)
df<- data.frame(Feature_A ,Feature_B ,Feature_C)
# Define UI for application
ui= fluidPage(
# Header or Title Panel
titlePanel(title = h4("Regression")),
sidebarLayout(
# Sidebar panel
sidebarPanel(
selectInput('ip', 'Select an Explanatory Variable', names(df)),
actionButton(inputId = "btn1",label="Regression Plot"),
actionButton(inputId = "btn2",label="Show Stats")),
# Main Panel
mainPanel("main panel", plotOutput("regplot"),
verbatimTextOutput("summary"))
))
server = function(input, output,session) {
#code for regression
lm_fit <- reactive({
lm(as.formula(paste0("Feature_A ~ ", input$ip)), data=df)
})
summary_stats <- eventReactive(input$btn2,{
summary(lm_fit())
})
regression_plot<- eventReactive(input$btn1, {
ggplot(data = df, aes(x = input$ip, y = Feature_A)) +
geom_point(color='blue') +
geom_smooth(method = "lm", se = FALSE)
})
#end of regression code
output$regplot <- renderPlot({
regression_plot()
})
output$summary <- renderPrint({
summary_stats()
})
}
shinyApp(ui,server)
这篇关于动态变量选择在shinyApp中的回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文