Anirudh Jain
Anirudh Jain

Reputation: 11

Create data partition function throwing this error - "y must have at least 2 data points"; while using it in reactive component in server.R shiny app

The app is asking the user to input predictor & dependent variables. For that I am using renderUI & uiOutput functions in server.R & ui.R files respectively. I am storing these inputs in predvar & depvar variables. Then i am using these variables in my reactive part of the code. This is where i think the problem of connection is between reactive code & user input variables. I have tried using caret::creatdatapartition instead of just createdatapartition. server.R code

model <- reactive ({
        prop = input$prop
        predictor = input$predvar
        dependent = input$depvar
        if(length(predictor)==0){return("Select atleast one predictor")} 
        if(input$ex==TRUE){data <- datasets::iris}
        else{file1 <- input$file
        data =  read.table(file =  file1$datapath,sep =",",header = TRUE)
        data = as.data.frame(data)}
        set.seed(69)
        inTrain <- createDataPartition(y=data$dependent,p=prop,list = FALSE) ## this line throws error
        train <- data[inTrain,]
        train <- train %>% select(predictor,dependent)
    train(dependent~.,data=data,method = "rpart")
    })

    output$model <- renderPrint({
      model()
)}
output$dependent <- renderUI({
      if(input$ex==TRUE){
        data = datasets::iris
        dependents <- select_if(data,is.factor)
        selectInput("depvar","Select the dependent variable",choices = colnames(dependents))
      }
      else{
        file1 <- input$file
        data =  read.table(file =  file1$datapath,sep =",",header = TRUE)
        dependents <- select_if(data,is.factor)
        selectInput("depvar","Select the dependent variable",choices = colnames(dependents))
      }
    })
    output$predictor <- renderUI({
      if(input$ex==TRUE){
        data = datasets::iris
        dependents <- select_if(data,is.numeric)
        checkboxGroupInput("predvar","Select the predictor variables",choices = colnames(dependents))
      }
      else{
        file1 <- input$file
        data =  read.table(file =  file1$datapath,sep =",",header = TRUE)
        dependents <- select_if(data,is.numeric)
        checkboxGroupInput("predvar","Select the predictor variables",choices = colnames(dependents))
      }
    })

concerning ui.R code

           checkboxInput("ex","Uncheck for using your own file",value = TRUE),
           fileInput("file", "Upload the *.csv file with headers"),
           uiOutput("dependent"),
           uiOutput("predictor"),
           sliderInput("prop",
                       "Enter the training data ratio",
                       min = .5,
                       max = 1,
                       value = .6,step = .05)
       )

Shiny app output image link

Upvotes: 1

Views: 1252

Answers (1)

Limey
Limey

Reputation: 12461

You haven't given us a simple self contained example, so we can't give you a tested answer. But I think I can see at least two problems with your server code.

First, the model reactive looks like it will run then the server function is first called, before your predvar and depvar inputs have been populated. That's going to case a problem, but it's easy to fix: just put req(input$depvar, input$predvar at the start of the reactive. That will make sure the rest of the code in the reactive runs only once you've got values for both these inputs.

Second, the line you identified,

inTrain <- createDataPartition(y=data$dependent,p=prop,list = FALSE)

Says "create a data partition and assign the parameter y the contents of the column named 'dependent' in the data.frame data. What you want to say is "... using the contents of the column whose name is given by the value of my local variable dependent...".

So try

inTrain <- createDataPartition(y=data[[dependent]],p=prop,list = FALSE)

instead.

You may have other issues as well, but they're the two I spotted from what you've posted so far.

Based on our discussion below, here is a MWE:

library(shiny) 
library(dplyr) 
library(datasets) 

ui <- shinyUI(
  fluidPage( 
    titlePanel("Classification tree model on iris dataset."), 
    sidebarLayout( 
      sidebarPanel( 
        uiOutput("dependent"), 
        uiOutput("predictor"), 
        sliderInput("prop", "Enter the training data ratio", min = .5, max = 1, value = .6,step = .05) ), 
      mainPanel( 
        verbatimTextOutput("model")
      ) 
    ) 
  )
)

server <- function(input, output) { 
  output$dependent <- renderUI({
    data = datasets::iris
    dependents <- select_if(data,is.factor)
    selectInput("dependent","Select the dependent variable",choices = colnames(dependents))
  })

  output$predictor <- renderUI({ 
    data = datasets::iris 
    predictors <- select_if(data,is.numeric) 
    checkboxGroupInput("predvar","Select the predictor variables", choices = colnames(predictors)) 
  }) 
}

shinyApp(ui, server)

You had selectInput("depvar", ... rather than selectInput("dependent", ... in your output$dependent. That's all that was wrong.

A couple of points to note:

  • Your simple self-contained example (SSE)wasn't bad, but everything to do with model was irrelevant as far as I could see, so could be removed. There are also far easier ways of preenting the code to us than in multiple comments! ;)
  • In your SSE, I don't think there's a need for uiOutput and renderUI. You could present your checkBoxGroup and selectInput directly in the fluidPage and then use updateSelectInput() and updateCheckBoxGroupInput in an observe or observeEevent (the latter depending on data) reactive. That removes one level of indirection and might make things simpler whoever maintains your code. [NB: if you do this, you will need to change server <- function(input, output) {...} to server <- function(input, output, session) {...}.
  • Next time, rather than saying "I tried, and it didn't work" (I'm paraphrasing: I can't see your comments whilst writing an answer), say "I tried, but I got the following error [Give the error text] at line number nnn".

Good luck!

Upvotes: 0

Related Questions