使用R Shiny中的动态输入构建线性回归

时间:2017-03-29 19:29:46

标签: r shiny

我正在尝试使用线性回归构建一个简单的闪亮应用程序,允许用户选择lm()函数中使用的独立变量和因变量,并最终绘制出几个图表。我目前坚持将输入传递给服务器端的lm()函数,并且能够打印出回归的摘要。任何人都可以帮助我解决我的逻辑/代码出错的问题。以下是代码

library(shiny)
library(data.table)

RegData <- as.data.table(read.table("/home/r2uphp/ShinyApps/IRViews/RegData.tsv", header = TRUE, stringsAsFactors = FALSE))

ui <- fluidPage(
  headerPanel("Regression and Time Series Analysis"), 
  sidebarPanel(
    p("Select the inputs for the Dependent Variable"),
    selectInput(inputId = "DepVar", label = "Dependent Variables", multiple = FALSE, choices = list("AvgIR", "YYYYMM", "SumCount", "AvgLTV", "AvgGFEE", "AvgRTC", "Date")),
    p("Select the inputs for the Independent Variable"),
    selectInput(inputId = "IndVar", label = "Independent Variables", multiple = FALSE, choices = list( "SumCount", "AvgIR", "YYYYMM", "AvgLTV", "AvgGFEE", "AvgRTC", "Date"))
  ),
  mainPanel(
    verbatimTextOutput(outputId = "RegSum"),
    verbatimTextOutput(outputId = "IndPrint"),
    verbatimTextOutput(outputId = "DepPrint")
    #plotOutput("hist")
  )
)

server <- function(input, output) {

    lm1 <- reactive({lm(paste0(input$DepVar) ~ paste0(input$IndVar), data = RegData)})

    output$DepPrint <- renderPrint({input$DepVar})
    output$IndPrint <- renderPrint({input$IndVar})
    output$RegSum <- renderPrint({summary(lm1())})

}

shinyApp(ui = ui, server = server)

This is the result of the shinyapp

以下是我正在使用的示例数据集:

     YYYYMM      AvgIR SumCount    AvgLTV     AvgGFEE   AvgRTC       Date
 1: 2015-10 0.04106781   180029 0.7531805 0.002424778 319.6837 2015-10-01
 2: 2015-11 0.04036154   160061 0.7380383 0.002722529 312.6314 2015-11-01
 3: 2015-12 0.04001407   145560 0.7392874 0.002425912 313.0351 2015-12-01
 4: 2016-01 0.04034078   147693 0.7396932 0.002600640 315.0238 2016-01-01
 5: 2016-02 0.04055688   142545 0.7345160 0.002449523 310.3950 2016-02-01

提前致谢!

1 个答案:

答案 0 :(得分:8)

您只需要正确构建公式。我不确定你的想法是什么paste0,但这里有更好的方法

lm1 <- reactive({lm(reformulate(input$IndVar, input$DepVar), data = RegData)})

reformulate()命令将为您构建正确的公式(请注意,自变量在函数中排在第一位。