如何在 Shiny 中更改回归模型表单下拉菜单中的预测变量?
Posted
技术标签:
【中文标题】如何在 Shiny 中更改回归模型表单下拉菜单中的预测变量?【英文标题】:How to change the predictor variable in regression model form drop-down menu in Shiny? 【发布时间】:2020-11-13 01:43:21 【问题描述】:我想在 Shiny 中有一个动态回归 qqplot,它有一个 x 值(预测变量)的下拉菜单。您可以在下面找到我的代码,其中我定义了一个 LM 函数,当我随后运行模型时,该函数将响应变量形式放在第一位,将预测变量从第二位放在第二位。问题是我在运行模型时必须准确地编写变量名称(请参见下面的代码),但我希望有 selectInput 函数,它将变量名称传递给模型。链接到我的 ShinyApp 以获得更清晰的图片(最后一个仪表板):https://schnappi.shinyapps.io/coronavirus/
代码如下:
回归模型函数:
ggplot(fit$model, aes_string(
x = names(fit$model)[2],
y = names(fit$model)[1],
label = names(fit$model)[3]
)) +
geom_point() + labs(x = "Population density (km2)", y = "Cases per 1M") +
stat_smooth(method = "lm") +
labs(title = paste(
"R2 =",
signif(summary(fit)$r.squared, 2),
" Slope =",
signif(fit$coef[[2]], 2),
" P =",
signif(summary(fit)$coef[2, 4], 2)
))
```
UI code:
tabItem(
tabName = "Dens",
titlePanel(h1(
"Population density and Covid-19 cases", align = "center"
)),
absolutePanel(
top = 130,
left = 250,
draggable = FALSE,
numericInput(
"num",
"x-axis cut off:",
max(join$Pop_density),
min = 1,
max = max(join$Pop_density)
)
),
absolutePanel(
top = 130,
left = 550,
draggable = FALSE,
numericInput(
"num2",
"y-axis cut off:",
max(join$TotCases_1M),
min = 1,
max = max(join$TotCases_1M)
)
),
absolutePanel(
top = 130,
left = 850,
draggable = FALSE,
selectInput("con", "Select continent:", choices =
join$Continent)
),
absolutePanel(
top = 130,
left = 1050,
draggable = FALSE,
selectInput("paraM", "Select parameter:", choices = colnames(join)) ## This is the part of the code that defines the predictor variable
),
absolutePanel(
top = 190,
left = 220,
width = 1700,
height = 500,
draggable = FALSE,
mainPanel(plotlyOutput("plotDens"))
)
)
This is part which RUN the regression model:
output$plotDens <- renderPlotly(
ggplotRegression(lm(
TotCases_1M ~ input$paraM, ## Here the LM model should recognize "input$paraM" as the column name but this does not work.
data = subset(join, Continent == input$con | input$con == "") %>%
filter(input$paraM > input$num &
TotCases_1M < input$num2)
))
)
THANK YOU.
【问题讨论】:
【参考方案1】:你没有提供ggplotRegression
的完整代码,但我相信你想要:
ggplotRegression(lm(
as.formula(paste0("TotCases_1M ~ ", input$paraM)),
......
【讨论】:
嗨斯蒂芬,它完美地工作。非常感谢。以上是关于如何在 Shiny 中更改回归模型表单下拉菜单中的预测变量?的主要内容,如果未能解决你的问题,请参考以下文章
Django Admin Cookbook-36如何更改下拉菜单中的ForeignKey显示文本
在 Shiny 中,避免 selectInput 下拉菜单与其下方的操作按钮重叠