Error data argument is of wrong type error when trying to analyse an uploaded csv file


#1
# This is the user-interface definition of a Shiny web application. You can
# run the application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
# 
#    http://shiny.rstudio.com/
#
library(shiny)
library(shinythemes)
library(ggplot2)
library(DT)
library(plotly)
library(dplyr)
ui <- fluidPage(
  theme =  shinythemes::shinytheme("readable"),
  tags$head(
    tags$style(HTML("
      @import url('//fonts.googleapis.com/css?family=Lobster|Cabin:400,700');
      
      h1 {
        font-family: 'Time New Roman', Times, serif;
        font-weight: 500;
        line-height: 1.1;
        color: #4169E1;
        center;

      }

    "))
  ),
  tags$img (src="487145302.jpg", width=1500, height=300),

  # App title ----
  headerPanel("SAMRAT INVENTROY FORECASTING APPLICATION"),
 # titlePanel("SAMRAT INVENTROY FORECASTING APPLICATION"),
  
  
  # Sidebar layout with input and output definitions ----
  sidebarLayout(
    
    # Sidebar panel for inputs ----
    sidebarPanel(
      
      #FILE INPUT
      fileInput('file1', 'Choose file to upload',
                accept = c(
                  'text/csv',
                  'text/comma-separated-values',
                  'text/tab-separated-values',
                  'text/plain',
                  '.tsv'
                )
      ),
      
      checkboxInput("header", "Header", TRUE),
      
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head"),
     
      
      
      selectInput("outcome", label = h3("Select the first ploting Variable:"),
                  choices = list("Sales" = "Sales",
                                 "Quantity" = "Quantity",
                                 "Discount" = "Discount",
                                 "Profit" = "Profit")
      ),
      
      selectInput("indepvar", label = h3("Select the Second ploting Variable:"),
                  choices = list("Sales" = "Sales",
                                 "Quantity" = "Quantity",
                                 "Discount" = "Discount",
                                 "Profit" = "Profit")
      
    ),
      
       hr(),
    radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
                 inline = TRUE),
    downloadButton('downloadReport'),
    hr(),
      
      # Input: Slider for the number of observations to generate ----
      sliderInput("n",
                  "Number of observations:",
                  value = 500,
                  min = 1,
                  max = 10000)
      
    ),
  
   
    
  
    
    
    # Main panel for displaying outputs ----
    mainPanel(
      #DT::dataTableOutput('contents'),
      
      # Output: Tabset data, salesanalysis, and predictions ----
      tabsetPanel(type = "tabs",
                  tabPanel(h2('CONTENTS'), dataTableOutput('contents')),
                  tabPanel("Sales Analysis", plotOutput("salesanalysis1"),
                           plotOutput("salesanalysis2"),plotOutput("salesanalysis3")),
                  tabPanel("Linear Modeling", plotOutput("linearmodel1"),uiOutput("linearmodel2")),
                  tabPanel("Predictions", plotOutput("predictions1"),plotOutput("predictions2"),plotOutput("predictions3")),
                  tabPanel("Predictions per Product", plotOutput("predictions4"), plotOutput("predictions5"), plotOutput("predictions6"))
                  
      )
      
    )

    )
  
)

#
# This is the server logic of a Shiny web application. You can run the 
# application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
# 
#    http://shiny.rstudio.com/
#

library(shiny)
library(shinythemes)
library(ggplot2)
library(DT)
library(plotly)
library(dplyr)


# Define server logic where processing takes place
shinyServer(function(input, output) {
  output$downloadReport <- downloadHandler(
    filename = function() {
      paste('my-report', sep = '.', switch(
        input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
      ))
    },
    
    content = function(file) {
      src <- normalizePath('report.Rmd')
      
      # temporarily switch to the temp dir, in case you do not have write
      # permission to the current working directory
      owd <- setwd(tempdir())
      on.exit(setwd(owd))
      file.copy(src, 'report.Rmd', overwrite = TRUE)
      
      library(rmarkdown)
      out <- render('report.Rmd', switch(
        input$format,
        PDF = pdf_document(), HTML = html_document(), Word = word_document()
      ))
      file.rename(out, file)
    }
  )
  mydata <- reactive({
    
    # input$file1 will be NULL initially. After the user selects
    # and uploads a file, head of that data file by default,
    # or all rows if selected, will be shown.
    
    inFile <- input$file1
    
    if (is.null(inFile))
      return(NULL)
    
    data <-read.csv(inFile$datapath, header = input$header)
    data
    
    #outputing the head or all data only
    if (input$disp == "head") {
      return(head(data))
    }
    else {
      return(data)
    }
  
  
})
  output$contents <- DT::renderDataTable({
    DT::datatable(mydata())       
  })
  
 
  
  sliderValues <- reactive({
    
    data.frame(
      Name = c("observations"),
      Value = as.character(c(input$outcome,
                             input$indepvar)),
      stringsAsFactors = FALSE)
    
  })
 
 #scatter plot of the data
  output$salesanalysis1 <-renderPlot({
    
    plot(data[,input$indepvar], data[,input$outcome], main="Scatterplot of the Data",
         xlab=input$indepvar, ylab=input$outcome,col = "#00FF00", pch=19)
    
  })
  
  
  #ploting a histogram
  output$salesanalysis2 <- renderPlot({
    hist(data[,input$indepvar], main="Histogram to show the frequency of the Data",col = "#75AADB", border = "white", xlab=input$indepvar)
  }, height=600, width=600)
  
 #creating a linear model

  eventReactive( input$file1, {
    
    model <- lm(Sales ~ Discount, data = data)
  
    
    output$linearmodel1 <- renderPlot({
      #summary(model)
      plot(model)
      abline(model)
      
    })
    #summary of the model
    output$linearmodel2 <- renderUI({
      summary(model)
    })
    #conducting the prediction
    output$predictions1 <- renderPlot({
     sales_pre <- predict(model, data = "Sales") 
     hist(sales_pre,xlab="Sales Predictions",col = "#75AADB", border = "white", main ="HISTOGRAM PLOT SHOWING THE SALES PREDICTIONS FREQUENCIES")
    })
    #scatter plot for the predictions
    output$predictions2 <- renderPlot({
      sales_pre <- predict(model, data = "Sales") 
      #plot(sales_pre, main ="SCATTER PLOT SHOWING THE SALES PREDICTIONS")
      scatter.smooth(sales_pre, data$Sales, main="Scatterplot of the Sales Predictions aganist Historical sales",col = "#00FF00", xlab="Sales Predictions", ylab="Historical Sales", pch=19)
      
    })
    #furniture predictions
    output$predictions4 <- renderPlot({
      newdata <- subset(data, data$Sales & data$Category == "Furniture")
      hist(predict(model, newdata),col = "#75AADB", main = "Funiture Sales Predictions", xlab = "Predicted furniture Sales")
    })
    #office predictions
    output$predictions5 <- renderPlot({
      newdata <- subset(data, data$Sales & data$Category == "Office Supplies")
      hist(predict(model, newdata),col = "#75AADB", main = "Office Supplies Sales Predictions", xlab = "Predicted Office Supplies Sales")
    })
    #technology predictions
    output$predictions6 <- renderPlot({
      newdata <- subset(data, data$Sales & data$Category == "Technology")
      hist(predict(model, newdata),col = "#75AADB", main = "Technology Sales Predictions", xlab = "Predicted Technology Sales")
    })
  })
  
  
  
})

#2

Hi, could you please provide a full stack trace?

That way we can know which line of the code is causing the problem.


#3

listening on http:// 127.0.0.0.1:7196
warning: Error in terms.formala: 'data' argument is of wrong type
79:
77:
72: observeEventHandler


#4

I'm not able to replicate your error, but the line above runs a model on data, yet I don't think data is ever set up as a data.frame that you'd be able to run a model over in your shiny app. Instead, it sets up an object mydata, no?

And then if data isn't set up as a data.frame usable by the lm() function, your shiny apps turns to the utils function data(), resulting in this wrong type error.