How to fix "Error in model.frame.default: variable lengths differ"

Hello,

I am preparing Regression calculator in shiny.Please find below code for your refer.

ui <- fluidPage(
  
  shinyFeedback::useShinyFeedback(),
  
  sidebarLayout(
    
    sidebarPanel(
      
      helpText("Upload Data"),
      
      fileInput("file", NULL, accept = c(".csv"), placeholder = ".csv file only"),
      
      selectInput("independ.variable", "Select Independent Variables[ x1, x2, ..]", choices = NULL, multiple = T),
      
      selectInput("depend.variable", "Select Dependent Variable[y]", choices = NULL)
    ),
    
    mainPanel(
      
      verbatimTextOutput("summary"),
      
      tableOutput("table"),          
      
      verbatimTextOutput("model")
    )
  )
)

server <- function(input, output, session) {
  
  reactive_dataset <- reactive({ 
    
    req(input$file)
    
    ext <- tools::file_ext(input$file$name)
    
    switch(ext, csv = vroom::vroom(input$file$datapath, delim = ","),
           validate("Invalid File; Please select .csv file"))
    })
  
  output$summary <- renderPrint({ summary(reactive_dataset())})
  
  observeEvent(reactive_dataset(),{
    
    choices <- colnames(reactive_dataset())
    
    updateSelectInput(session, "independ.variable", choices = choices)
    
  })
  
  observeEvent(reactive_dataset(), {
    
    choices <- colnames(reactive_dataset())
    
    updateSelectInput(session, "depend.variable", choices = choices)
  })
  
  reactive_dataframe <- reactive({ 
    
    req(input$independ.variable, input$depend.variable)
    
    reactive_dataset() %>%
      
      select(input$independ.variable, input$depend.variable)
    
    })
  
  output$table <- renderTable(head(reactive_dataframe()))
  
  
  

  
  output$model <- renderPrint({ 
    
    result <- reactive_dataframe() %>% map(~lm(input$depend.variable ~ ., data = reactive_dataframe()))
    
    summary(result)
    
    })
  
}

However i am getting "Error in model frame default variable lengths differ" in output$model.

Any suggestion, help will be appreciated !!

I think you want to do something like

    result <-  map(names(reactive_dataframe()),
                   ~lm(as.formula(paste(input$depend.variable," ~ ",.)),
                       data = reactive_dataframe()))

also recommend that when you share example code, you list your libraries

library(shiny)
library(shinyFeedback) # although this is not relevant to the example
library(tidyverse)

Thank you for your reply..
Now i am getting "Error in Part_Weight: could not find function "Part_Weight" ..

Theres no mention of any such function in the code that you shared.
shiny usually gives you a traceback telling you the line number of your code that started the error.
Do you see that in this case?

Yeah ..right..
Part_weight is one of the independent variable in the dataset.
It is considering Part_Weight as a function rather a variable.. Do you have any idea why this is happening?

this only happens when you choose Part_Weight to be in your list of dependents , and not if you use any other number of variables as dependents ?

Well .. even if I remove "Part_Weight" and inserted some other Variables.... It says "Object not found".

try this in your console to save a csv. that way we can diagnose if you have a data problem or a code problem or something else.

write.csv(iris , "iris.csv")

and then use the csv this as the input to the code we are discussing. Does it still give problematic behaviour with the iris data ?

1 Like

Wow.. It is working for "iris" dataset. I found the error it is because of the "(" present in Part_Weight column header.

Thank you so much.. also figured out that there is no need for map function as well.

Below code runs smoothly :-

result <-  lm ( as.formula( paste( input$depend.variable, "~", paste(input$independ.variable, collapse = "+"))),
             
             data = reactive_dataframe())

Once again thank you for your help !!! Appreciate

Sorry to bother you again.. Need your help !!

So now i am able to create the linear model. The issue now is that i want to predict the dependable variable as soon as the user enters independent variables.. Below is the code I have used.

ui <-  fluidPage(

sidebarLayout(

sidebarPanel(
  
  helpText("Upload load.."),
  
  fileInput("file", NULL, accept = c(".csv"), placeholder = ".csv file only"),
  
  selectInput("independ.variable", "Select Independent Variable [ x1, x2,..]", choices = NULL, multiple = T),
  
  selectInput("depend.variable", "Select Dependent Variable [ y ]", choices = NULL, multiple = F),
  
  uiOutput("var"),
  
  actionButton("go", "GO"),
  
  verbatimTextOutput("price")
  
)

output$var <- renderUI({

  my_cols <- colnames(reactive_dataframe())
  
  ui_elems <- purrr::map(my_cols, ~{
    
    if(class(reactive_dataframe()[[.x]]) %in% c("factor", "character")){
      
      output <- textInput(
        
        inputId = paste("input", .x, sep = "_"),
        
        label = .x,
        
        value = NULL
      )
    } else if(class(reactive_dataframe()[[.x]]) %in% c("integer", "numeric")){
      
      output <- numericInput(
        
        inputId = paste("input", .x, sep = "_"),
        
        label = .x,
        
        value = NULL
      )
    } else output <- NULL
      
    return(output)
  })
  
  return(tagList(ui_elems))
})


reactive_price <- eventReactive(input$go, {
  
  req(reactive_dataframe())
  
  mycols <- colnames(reactive_dataframe())
  
  myinputs <- paste("input", mycols, sep = "_") 
  
  reactive_dataframe() %>% 
    
    mutate(pred = map2())    
  } 
    })      
  
})

I got stuck in the Predict function. Do you have idea how i can do it?

My advice is to practice using predict function, in simple scripts outside of shiny first.

Actually .. i did.. it works but .. I don't see how i can use the below function when the Inputs are also interactive ..like I showed you in above code.. I did some search to see is there any way by purrr package but i am not able to get it..

  predict(result, data.frame(Plant = factor(input$plant), Number.of.Functions =as.factor(input$func), Function.Type = as.factor(input$type) ))

what are you trying to predict over ? a hold out set? , the original model training data ?

Okay ... I will just share with you my thought process. I am preparing regression calculator .

  1. The user will upload the data
  2. Then the application will run and print the summary of the data.
  3. The user will select the independent variables and dependent variables.
  4. As soon as there is a significant correlation . The user will click on model button and linear regression model will be generated .
  5. Then with the help render UI. Dynamic numericInputs will be generated on the basis of selected Independent variables and then the user will enter the values to calculate the predicted price.

So I have been able to do till storing the regression model and preparing dynamic inputs. I am stuck at the last part. How can i use the values entered inside the dynamic input by the user to predict the price.

Below is the code i used to populate the dynamic input on the basis of column selection by the user:

ui <- fluidpage(uiOutput("var"))

 output$var <- renderUI({
  
  my_cols <- colnames(reactive_dataframe())
  
  ui_elems <- purrr::map(my_cols, ~{
    
    if(class(reactive_dataframe()[[.x]]) %in% c("factor", "character")){
      
      output <- textInput(
        
        inputId = paste("input", .x, sep = "_"),
        
        label = .x,
        
        value = NULL
      )
    } else if(class(reactive_dataframe()[[.x]]) %in% c("integer", "numeric")){
      
      output <- numericInput(
        
        inputId = paste("input", .x, sep = "_"),
        
        label = .x,
        
        value = NULL
      )
    } else output <- NULL
      
    return(output)
  })
  
  return(tagList(ui_elems))
})

and I want to use above variables and ID to predict the model.

Please let me know it you want more info. or any part of code.

Thanks

You're most likely to get the help you require if you make a reprex. keep it as simple as possible.
Omit the ability to load a users csv. assume that iris is loaded.
We can then collaborate on a solution for the narrowest task.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.