nab
nab

Reputation: 23

How to define formula dynamically from select input ( multiple = TRUE) in R shiny

I am trying to define a formula for multinomial logistic regression , it should take the input from drop down list upto maximum 6 Independent variables. ( SelectInput , Multiple = TRUE) in R Shiny. Not able to figure out how to resolve this ..

Here are sample code... Formula

Multiformula <- reactive ({ as.formula(paste(input$outcome,'~'input$predictor) })

Model

MultiModel <- reactive({
    multinom(Multiformula(), data = filtered())
  })

Above code works for single variable, however for more than one independent variables the approach may be different. I tried the below but no luck

indvar6 <- reactive({
  filter(forest_data_model[,input$predictor])
  })

Redefined the formula... but it didn't work

Multiformula <- reactive ({as.formula(paste(input$outcome,'~'indvar6())})

Any guidance will be highly appreciated...thanks

Upvotes: 2

Views: 1388

Answers (1)

akrun
akrun

Reputation: 887501

We could try

library(shiny)
library(nnet)
library(foreign)
fmnom <- function(data  = NULL, depVar, indepVar) {

  ui <- fluidPage(
    headerPanel("Multinomial analysis"), 
    sidebarPanel(
      p("Select inputs for the Dependent Variable"),
      selectInput(inputId = "dep", label = "Dependent Variables", multiple = FALSE, 
                       choices = as.list(depVar)),
      p("Select input for the Independent Variable"),
      selectInput(inputId = "indep", label = "Independent Variables", 
                  multiple = TRUE, choices = as.list(indepVar), selected = indepVar[1])
    ),
    mainPanel(
      verbatimTextOutput(outputId = "RegOut"),
      verbatimTextOutput(outputId = "IndPrint"),
      verbatimTextOutput(outputId = "DepPrint")

    )
  )

  server <- function(input, output) {

    mlt <- reactive(
                     {multinom(reformulate(input$indep, input$dep), data = data)})

    output$DepPrint <- renderPrint({input$dep})
    output$IndPrint <- renderPrint({input$indep})
    output$RegOut <- renderPrint({summary(mlt())})

  }



  shinyApp(ui= ui, server = server)
}

-data

ml <- read.dta("https://stats.idre.ucla.edu/stat/data/hsbdemo.dta")

-run shiny

fmnom(ml, depVar = c("prog", "schtyp"), indepVar = c("ses", "read", "write") )

-output single independent variable

enter image description here

-output multiple independent variables

enter image description here

Upvotes: 3

Related Questions