Error in as.data.frame.default: cannot coerce clas

2019-02-20 09:06发布

问题:

I am having an issue with creating a data frame from a reactive in Shiny. The app allows a user to upload some data hence the dataset is reactive. It will then allow the user to select the input and output variables which will be passed onto a regression and a plot is generated. I keep getting an error stating:

Error in as.data.frame.default: cannot coerce class "c("reactiveExpr", "reactive")" to a data.frame

I believe that its coming from my d.f variable which is supposed to be a dataframe of the user uploaded data. I have not been able to secure a workaround after scouring the internet. Any help would be appreciated. The code so far is below.

library(shiny)
library(triangle)
library(readxl)
library(leaps)
library(coefplot)
library(relaimpo)
library(data.table)
library(XLConnect)
library(xlsx)

ui <- fluidPage(

  titlePanel("Hi"),
  sidebarLayout(position = "left",
                sidebarPanel(
                  conditionalPanel(condition = "input.tabs1==1",
                                   tags$style(type='text/css', ".well { max-width: 20em; }"),
                                   # Tags:
                                   tags$head(
                                     tags$style(type="text/css", "select[multiple] { width: 100%; height:10em}"),
                                     tags$style(type="text/css", "select { width: 100%}"),
                                     tags$style(type="text/css", "input { width: 19em; max-width:100%}")
                                   ),

                                   # Select filetype:
                                   selectInput("readFunction", "Function to read data:", c(
                                     # Base R:
                                     "read.table",
                                     "read.csv",
                                     "read.csv2",
                                     "read.delim",
                                     "read.delim2",
                                     "readWorksheet",
                                     "read_excel",
                                     "read.xlsx"

                                   )),

                                   # Argument selecter:
                                   htmlOutput("ArgSelect"),

                                   # Argument field:
                                   htmlOutput("ArgText"),

                                   # Upload data:
                                   fileInput("file", "Upload data-file:"),

                                   # Variable selection:
                                   htmlOutput("varselect"),

                                   br(),

                                   uiOutput("invar"),
                                   br(),
                                   uiOutput("outvar"),

                                   textInput("name","Dataset name:","Data")),
                  conditionalPanel(condition = "input.tabs1==2",
                                   #fileInput('file', 'Choose file to upload.'),
                                   #selectizeInput('invar',"Select Invar", choices = varnames, multiple = TRUE),
                                   #selectizeInput('outvar',"Select Outvar", choices = predictors, multiple = FALSE),
                                   radioButtons('LM',"Select Regression",choices = list("LM" = 1, "LM2" = 2),selected = 1)




                )),
                mainPanel(
                  tabsetPanel(id="tabs1",
                              tabPanel("Data File",value = 1,tableOutput("table")),
                              tabPanel("Plot",value=2,tableOutput("Data"),plotOutput("Plot"))       
                  )
                )

))



server<-function(input, output) {
  options(shiny.maxRequestSize=30*1024^2)

  ### Argument names:
  ArgNames <- reactive({
    Names <- names(formals(input$readFunction)[-1])
    Names <- Names[Names!="..."]
    return(Names)
  })

  # Argument selector:
  output$ArgSelect <- renderUI({
    if (length(ArgNames())==0) return(NULL)

    selectInput("arg","Argument:",ArgNames())
  })

  ## Arg text field:
  output$ArgText <- renderUI({
    fun__arg <- paste0(input$readFunction,"__",input$arg)

    if (is.null(input$arg)) return(NULL)

    Defaults <- formals(input$readFunction)

    if (is.null(input[[fun__arg]]))
    {
      textInput(fun__arg, label = "Enter value:", value = deparse(Defaults[[input$arg]])) 
    } else {
      textInput(fun__arg, label = "Enter value:", value = input[[fun__arg]]) 
    }
  })


  ### Data import:
  Dataset <- reactive({
    if (is.null(input$file)) {
      # User has not uploaded a file yet
      return(data.frame())
    }

    args <- grep(paste0("^",input$readFunction,"__"), names(input), value = TRUE)

    argList <- list()
    for (i in seq_along(args))
    {
      argList[[i]] <- eval(parse(text=input[[args[i]]]))
    }
    names(argList) <- gsub(paste0("^",input$readFunction,"__"),"",args)

    argList <- argList[names(argList) %in% ArgNames()]

    Dataset <- as.data.frame(do.call(input$readFunction,c(list(input$file$datapath),argList)))
    return(Dataset)
  })

  # Select variables:
  output$varselect <- renderUI({

    if (identical(Dataset(), '') || identical(Dataset(),data.frame())) return(NULL)

    # Variable selection:    
    selectInput("vars", "Variables to use:",
                names(Dataset()), names(Dataset()), multiple =TRUE)            
  })

  # Show table:
  output$table <- renderTable({

    if (is.null(input$vars) || length(input$vars)==0) return(NULL)

    return(Dataset()[,input$vars,drop=FALSE])
  })

  #################################################################################

  varnames<-reactive({
    names(input$readFunction)
  })

  output$invar<-renderUI({
    selectizeInput('invar',"Select Invar", choices = names(Dataset()), multiple = TRUE)
  })

  output$outvar<-renderUI({
    selectizeInput('outvar',"Select Outvar", choices = names(Dataset()), multiple = TRUE)

  })

  d.f<-Dataset

  output$Plot <- renderPlot({    

    SelectedVars <- input$invar
    vartopredict <- input$outvar

      fmla <- reformulate(SelectedVars, response = vartopredict)
      pred.model=lm(fmla,d.f)
      plot(pred.model)
      abline(a=0,b=1,col="red")


  })
}

  shinyApp(ui = ui, server = server)

回答1:

As Chi Pak has mentioned, reactive expressions must contain () at the end. Changing d.f to d.f() fixes the issue.