因此,我构建了一个闪亮的应用程序,可让您根据数据集中变量的任意组合创建散点图。它还在单独的选项卡上输出回归模型的摘要。
基本上,我希望有一个选项可以向我的散点图添加回归线。这将基于从UI中选择的用于创建散点图的输入。我做了几次尝试,但没有成功。这是我到目前为止的工作代码:
pageWithSidebar(
titlePanel("Plotting weather trends 2010 - 2014"),
sidebarPanel(
selectInput("xCol", "Please select an x variable", names(DF2)),
selectInput("yCol", "Please select a y variable", names(DF2)),
checkboxInput("line", "Show regression line?", value = TRUE),
selectInput("plot_type", "Select a secodary plot for X variable", choices = c("Boxplot", "Histogram"))),
mainPanel(tabsetPanel(type = "tabs",
tabPanel("Plots", (plotOutput("plot1")), plotOutput("plot2")),
tabPanel("Regression Model Summary", verbatimTextOutput(outputId = "RegSum"))
)
)
))
server = function(input, output){
DF3 = reactive({DF2[, c(input$xCol, input$yCol)]})
output$plot1 = renderPlot({plot(DF3(),
main = "Histogram of select variables")})
output$plot2 = renderPlot({
if (input$plot_type == "Boxplot") {boxplot(DF2[,input$xCol], main = "boxplot of X variable")}
if (input$plot_type == "Histogram") {hist(as.numeric(unlist(DF2[,input$xCol])),main = "Histogram of X variable", xlab = "X variable")}
})
lm1 <- reactive({lm(reformulate(input$xCol, input$yCol), data = DF2)})
output$RegSum <- renderPrint({summary(lm1())})
}
shinyApp(ui = ui, server = server)
先前的尝试包括添加abline(lm)函数以从UI接收输入,但无济于事。
任何帮助将不胜感激。
答案 0 :(得分:0)
使用abline
是正确的方法。我想您的问题是您如何指定lm
函数:如果用户选择两个变量“ xCol”和“ yCol”,则将它们引号传递给Shiny的服务器。但是,lm
函数要求使用y ~ x
形式的公式表示法。为了解决这个问题,我将写lm(get(input$yCol) ~ get(input$xCol), data=DF3())
。这样R就可以在数据集中而不是全局环境中进行搜索。
以下是基于内置mtcars数据集的可复制示例:
library(shiny)
ui <- fluidPage(
selectInput("xCol", "Please select an x variable", names(mtcars)),
selectInput("yCol", "Please select a y variable", names(mtcars)),
checkboxInput("line", "Show regression line?", value = TRUE),
plotOutput("plot")
)
server <- function(input, output, session) {
data <- reactive({mtcars[, c(input$xCol, input$yCol)]})
output$plot <- renderPlot({
plot(data())
if(input$line) {
model <- lm(get(input$yCol) ~ get(input$xCol), data=data())
abline(model)
}
})
}
shinyApp(ui, server)