Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable names to model in shiny app

Tags:

r

shiny

I'm creating an app for simple linear regression using shiny. I want to pass variable names to the model automatically. I tried variable inputs from users. code in server.R is

lm(paste(input$dependent," ~ ",input$independent), data=data1())

and

lm(paste0(input$dependent) ~ paste0(input$independent), data=data1())

And also tried below syntax;

lm(names(data1()[2]) ~ names(data1()[1]) , data=data1())

these are all not working...
How can I pass variable names to the model?
Thanks in advance...

like image 987
Punith Avatar asked Feb 16 '23 07:02

Punith


1 Answers

Your example isn't full enough for me to understand what errors you are running into, but I think this should do the trick:

    lm(as.formula(paste(input$dependent," ~ ",paste(input$independent,collapse="+"))),data=dat)

A junky test shows that this is able to create dynamic models (although needs a bit of tweaking in other areas):

ui.R

library(shiny)

shinyUI(pageWithSidebar(
  headerPanel("Test Shiny App"),

  sidebarPanel(
    selectInput("dependent", "Dependent Variable:", c("x","y","z")),
    uiOutput("independent")
  ),

  mainPanel(tableOutput("regTab"))
))

server.R

library(shiny)

dat <- data.frame(x=rnorm(100),y=rnorm(100),z=rnorm(100))

shinyServer(function(input, output, session) {

  output$independent <- renderUI({
    checkboxGroupInput("independent", "Independent Variables:",names(dat)[!names(dat) %in% input$dependent],names(dat)[!names(dat) %in% input$dependent])
  })

  runRegression <- reactive({
    lm(as.formula(paste(input$dependent," ~ ",paste(input$independent,collapse="+"))),data=dat)
  })

  output$regTab <- renderTable({
    if(!is.null(input$independent)){
      summary(runRegression())$coefficients
    } else {
      print(data.frame(Warning="Please select Model Parameters."))
    }
  })

})
like image 191
David Avatar answered Feb 18 '23 12:02

David