Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build Linear Regression with dynamic inputs in R Shiny

Tags:

r

shiny

I am trying to build a simple shiny app using a linear regression that allows the user to select both the independent and dependent variables that are used in the lm() function and eventually plot out a few charts as well. I am currently stuck on passing the inputs to the lm() function on the server side of shiny and being able to print out the summary of the regression. Can anyone assist me in where my logic/code is going wrong. Below is the code

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

Here is a sample dataset that I am using:

     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

Thanks in advance!

like image 839
Jst2Wond3r Avatar asked Mar 29 '17 19:03

Jst2Wond3r


1 Answers

You just need to build your formula correctly. I'm not sure what you think paste0 does, but here's a better way

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

The reformulate() command will build the correct formula for you (note that the independent variables come first in the function.

like image 93
MrFlick Avatar answered Oct 15 '22 21:10

MrFlick