我正在练习使用alr4包中的baeskel
数据创建一些闪亮的应用程序。我的目标是创建一个selectInput下拉菜单,这样用户就可以选择要绘制的回归线。我不确定如何在服务器部分安排代码。到目前为止,对于我创建的一条绘制线:
library(alr4)
data("baeskel")
ui <- fluidPage(
sidebarLayout(position="left",
sidebarPanel("sidebarPanel", width=4),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("baeskal Data", tableOutput("table")),
tabPanel("Polynomial Regression", plotOutput("polyplot"))
)
)
)
)
server <- function(input, output){
output$table <- renderTable({
baeskel
})
x <- baeskel$Sulfur
y <- baeskel$Tension
output$polyplot <- renderPlot({
plot(y~x, pch = 16,xlab="Sulfur",ylab="Tension",
main = "Observed Surface Tension ofnLiquid Copper with Varying Sulfur Amount")
linear_mod = lm(y~x, data = baeskel)
linear_pred = predict(linear_mod)
lines(baeskel$Sulfur, linear_pred,lwd=2,col="blue")
})
}
shinyApp(ui = ui, server = server)
它真的很好用。我的下一个目标是添加另一条回归线,如下所示:
quadratic_mod <- lm(Tension ~ poly(Sulfur, 2), data = baeskel)
quadratic_pred <- predict(quadratic_mod)
lines(baeskel$Sulfur, quadratic_pred, lwd = 2, col = "green")
然而,我想使用如下的selectInput功能(尚未在边栏布局中显示(:
selectInput(inputId = , "Choose Regression Line:", c("Linear", "Quadratic"))
我不知道如何选择inputId,这样它就可以从每条回归线中收集信息。
这里有一个工作示例,它允许以闪亮的方式绘制不同的预测模型。
在ui
中,添加selectInput
以选择回归线的类型。
在server
中,您可以添加一个if
语句来检查此输入,并确定要根据数据构建哪个模型。
将相应地绘制来自模型和线的适当预测。
library(alr4)
library(shiny)
data("baeskel")
ui <- fluidPage(
sidebarLayout(position="left",
sidebarPanel(
"sidebarPanel", width=4,
selectInput(inputId = "reg_line", "Choose Regression Line:", c("Linear", "Quadratic"))),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("baeskal Data", tableOutput("table")),
tabPanel("Polynomial Regression", plotOutput("polyplot"))
)
)
)
)
server <- function(input, output){
output$table <- renderTable({
baeskel
})
output$polyplot <- renderPlot({
plot(Tension ~ Sulfur, data = baeskel, pch = 16, xlab="Sulfur", ylab="Tension",
main = "Observed Surface Tension ofnLiquid Copper with Varying Sulfur Amount")
if(input$reg_line == "Linear") {
baeskel_mod = lm(Tension ~ Sulfur, data = baeskel)
} else {
baeskel_mod = lm(Tension ~ poly(Sulfur, 2), data = baeskel)
}
baeskel_pred = predict(baeskel_mod)
lines(baeskel$Sulfur, baeskel_pred, lwd=2, col="blue")
})
}
shinyApp(ui = ui, server = server)