mmohd
mmohd

Reputation: 21

Object Not found error in my Shiny server.R code

I am new to R programming. When I execute my shiny app code, I get the error "Error in func() : object 'file3' not found". Any suggestions on how to resolve this? Below is the server.R code where I have the error:

library(shiny)
shinyServer(function(input, output) {

  reactive ({ 
  if(is.null(input$file1))     return(NULL) 
  fl1 <- paste("file:///",input$file1,sep='') 

  if(is.null(input$file2))     return(NULL) 
  fl2 <- paste("file:///",input$file2,sep='')

  file1 <- read.table(fl1,sep=',',header=TRUE)
  file2 <- read.table(fl2,sep=',',header=TRUE) 

  library(sqldf) 
  options(gsubfn.engine = "R") 

  file3 <- sqldf('SELECT * FROM file2 UNION ALL SELECT * FROM file1') 

  })
  output$text1 <- renderTable({ file3 })

})

Upvotes: 0

Views: 2758

Answers (1)

RickTastic
RickTastic

Reputation: 300

I am answering based on the code provided, since you reference input$xx, I assume that you have a ui.R file :-). Also if your files are uploaded files you will need to handle them using shiny::observeEvent, otherwise input$file1 and input$file2 will always be NULL.

You also should ensure that the UI object with inputID = "text1" is defined as a dataTable output rather than a textOutput. So something like this: shiny::dataTableOutput("text1"). This will ensure that your input is parsed correctly.

I have also fixed some of your styling to make you code more readable. See google R Style Guide. You can try the following, taking into account the above:

library(shiny)
library(sqldf) 
options(gsubfn.engine = "R")

shinyServer(function(input, output) {
  getData <- reactive ({ 
    if(is.null(input$file1))  return(NULL) 
    fl1 <- paste("file:///", input$file1, sep = '') 

    if(is.null(input$file2))  return(NULL) 
    fl2 <- paste("file:///", input$file2, sep='')

    file1 <- read.table(fl1, sep = ',', header = TRUE)
    file2 <- read.table(fl2, sep = ',', header = TRUE)  

    file3 <- sqldf('SELECT * FROM file2 UNION ALL SELECT * FROM file1')

    return(file3)
  })

  output$text1 <- shiny::renderDataTable({ getData() })
})

I hope this helps. You may also want to try using DT::renderDataTable instead of shiny::renderDataTable

Upvotes: 1

Related Questions