rshinyregressionselectinput

Using R Shiny for Multiple Linear Regression (SelectInput --> multiple=TRUE)


I'm having some trouble getting my R Shiny code to produce a dynamic dashboard where the user can select 1 or more independent variables in a linear regression model and print the results. I've been able to successfully follow examples where the user only inputted one independent variable, but with multiple independent variables, I have not found the same luck. I'm not sure what I am doing wrong, but I get an error that reads, "invalid term in model formula".

Below is the code I've used so far:

library(shinythemes)
library(shinyWidgets)
library(shiny)
library(shinydashboard)


#data(mtcars)

AttributeChoices=c("cyl","disp","hp","drat","wt","qsec","vs")


# Define UI for application
ui = fluidPage(
    navbarPage("R Shiny Dashboard",
        tabPanel("Welcome",
                 tabName = "welcome",
                 icon=icon("door-open"),

          fluidPage(theme=shinytheme("cerulean"),
                    h1("Welcome to my Shiny Dashboard!"),
                    br(),
                    p(strong(tags$u("What is this dashboard all about?"))),
                    p("I'm going to do stuff."),  
                    br(),
                    p(strong(tags$u("Here's another question."))),
                    p("Here's my answer."),
                    br(),
                    p(strong(tags$u("How can I use this dashboard?"))),
                    p("You can click on any of the tabs above to see a different analysis of the data.")
                    )),

              tabPanel("Regression",
                       tabname="regression",
                       icon=icon("calculator"),
                       selectInput(inputId = "indep", label = "Independent Variables", 
                                   multiple = TRUE, choices = as.list(AttributeChoices), selected = AttributeChoices[1]),
                       verbatimTextOutput(outputId = "RegOut")


          )
        ))
# Define server logic 
server <- function(input, output) {

#-------------------REGRESSION-------------------#


  lm_reg <- reactive(
  lm(as.formula(paste(mtcars$mpg," ~ ",paste(input$indep,collapse="+"))),data=CFD)
  )


  output$RegOut = renderPrint({summary(lm_reg())})

}

# Run the application 
shinyApp(ui = ui, server = server)

Reading similar posts on StackOverflow seem to suggest the problem might be with the column names having spaces, but that's not the case here in this example. I am not sure how to resolve this issue. Can anyone help point me in the right direction? Thank you!


Solution

  • Here you go, I like to use the recipe package for problems like this instead of relying on very hard string manipulation, the trick is to use the !!! operator, you can even get fancy and let the user pass some select helpers

    library(shinythemes)
    library(shinyWidgets)
    library(shiny)
    library(shinydashboard)
    library(recipes)
    #data(mtcars)
    
    AttributeChoices=c("cyl","disp","hp","drat","wt","qsec","vs")
    
    
    # Define UI for application
    ui = fluidPage(
      navbarPage("R Shiny Dashboard",
                 tabPanel("Welcome",
                          tabName = "welcome",
                          icon=icon("door-open"),
    
                          fluidPage(theme=shinytheme("cerulean"),
                                    h1("Welcome to my Shiny Dashboard!"),
                                    br(),
                                    p(strong(tags$u("What is this dashboard all about?"))),
                                    p("I'm going to do stuff."),  
                                    br(),
                                    p(strong(tags$u("Here's another question."))),
                                    p("Here's my answer."),
                                    br(),
                                    p(strong(tags$u("How can I use this dashboard?"))),
                                    p("You can click on any of the tabs above to see a different analysis of the data.")
                          )),
    
                 tabPanel("Regression",
                          tabname="regression",
                          icon=icon("calculator"),
                          selectInput(inputId = "indep", label = "Independent Variables", 
                                      multiple = TRUE, choices = as.list(AttributeChoices), selected = AttributeChoices[1]),
                          verbatimTextOutput(outputId = "RegOut")
    
                 )
      ))
    # Define server logic 
    server <- function(input, output) {
    
      #-------------------REGRESSION-------------------#
    
    recipe_formula <- reactive(mtcars %>%
        recipe() %>%
        update_role(mpg,new_role = "outcome") %>%
        update_role(!!!input$indep,new_role = "predictor") %>% 
        formula())
    
      lm_reg <- reactive(
        lm(recipe_formula(),data = mtcars)
      )
    
    
      output$RegOut = renderPrint({summary(lm_reg())})
    
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)