saurabh shah
saurabh shah

Reputation: 48

Error with plotting graph using the data from an uploaded file

I am getting an error invalid first argument before I upload any csv file.

After uploading the csv file the app works properly, is there any way to remove this error.

server.R

library(ggplot2)
library(shiny)
shinyServer(func <- function(input,output){


  data <- reactive({
    file1 <- input$file
    if(is.null(file1)){return()}
    read.csv(file=file1$datapath, header=TRUE)
  })

  output$xselect <- renderUI({
    selectInput("xcol","X variable",names(data()))
  })

  output$yselect <- renderUI({
    selectInput("ycol","Y variable", names(data()))
  })



  output$p <- renderPlot({
    data()
    plot(get(input$xcol), get(input$ycol))
  })


  }
)

Upvotes: 3

Views: 144

Answers (2)

zx8754
zx8754

Reputation: 56149

We could check if the object exists:

validate(need(data(), "Dataframe not found"))

Or we could hide all error messages:

tags$style(type="text/css",
           ".shiny-output-error { visibility: hidden; }",
           ".shiny-output-error:before { visibility: hidden; }")

Upvotes: 2

Mike Wise
Mike Wise

Reputation: 22817

Not exactly a complete example, but close enough I guess.

I think you are looking for the validate command. Here is a more complete example using that:

library(ggplot2)
library(shiny)

ui <- fluidPage(
    textInput("xcol", "xcol:", "wt"),
    textInput("ycol", "ycol:", "mpg"),
    fileInput("file", label = "csv file"),
    plotOutput("p")
) 

server <- function(input,output){
  data <- reactive({
    file1 <- input$file
    if(is.null(file1)){return()}
    read.csv(file=file1$datapath, header=TRUE)
  })
  output$xselect <- renderUI({
    selectInput("xcol","X variable",names(data()))
  })
  output$yselect <- renderUI({
    selectInput("ycol","Y variable", names(data()))
  })
  output$p <- renderPlot({
    validate(need(input$file,"need filename"))
    df <- data()
    plot(df[[input$xcol]], df[[input$ycol]],
         xlab=input$xcol,ylab=input$ycol)
  })
} 
shinyApp(ui=ui, server=server)

yielding

enter image description here

Upvotes: 2

Related Questions