Validate to Read Upload File in Shiny

At the very bottom is now posted the consummate resolved code, reflecting the solution offered by M. Jagan. This code offers the full cycle of both data uploads (with robust data validation) and downloads of user inputs. You lot can come across how the try() office "tests" the upload to avert unnecessarily crashing the App.

When running the below code, the user can upload and download input data. The user tin download and save inputs, and later retrieve those inputs via upload. I'm trying to improve the upload validation considering in reality it will exist very piece of cake for the user to select an wrong file and I'd rather flag with a alarm rather than have the App crash similar it does at present.

All downloads are saved as a 2-column matrix with headers of X and Y. That (and the fact that information technology's a CSV) are my fundamental upload validations per the beneath code. The App correctly downloads and uploads CSV data equally shown in epitome 1 (download) and image two (upload) below, simply crashes when it tries uploading incorrectly formatted CSV information per image 3 below.

And then my questions are:

  1. How do I specify which columns in the csv file to look for the "Ten" and "Y" headers? Currently it reads everywhere for 10 and Y headers. I tried read.csv(...colClasses=c(NA, NA))) as shown beneath, I also tried read.csv(...)[ , 1:2] and neither one works.
  2. More than mostly, is there a manner to arrest the upload if it would otherwise cause an fault or crash? Sort of like if(iserror(...)) in Excel
  3. OK at present I'yard pushing it, please feel gratuitous to ignore this if this is as well much. Whatever way to move the upload warning into modalDialog? I tin ever move this to another post if I tin't effigy it out, later resolving the above.

MWE lawmaking:

          library(dplyr) library(shiny) library(shinyMatrix)  interpol <- function(a, b) { # a = periods, b = matrix inputs   c <- rep(NA, a)   c[1] <- b[i]   c[a] <- b[2]   c <- approx(seq_along(c)[!is.na(c)], c[!is.na(c)], seq_along(c))$y    return(c) }  ui <- fluidPage(   sidebarLayout(     sidebarPanel(       fileInput("file1", "Optionally choose input file (csv)", accept = ".csv"),       sliderInput('periods', 'Periods to interpolate over:', min=ane, max=ten, value=10),       matrixInput("matrix1",                    value = matrix(c(1,five),                            ncol = 2,                            dimnames = list("Interpolate",c("Ten","Y"))                   ),                   cols =  listing(names = TRUE),                   course = "numeric"       ),       downloadButton("download")     ),     mainPanel(       tableOutput("contents"),       plotOutput("plot")     )   ) )  server <- function(input, output, session) {      input_file <- reactive({     file <- input$file1     ext <- tools::file_ext(file$datapath)     req(file)          if(is.zilch(file))       return(Nothing)          file_contents <- read.csv(file$datapath,header=True,colClasses=c(NA, NA))     required_columns <- c('X','Y')     column_names <- colnames(file_contents)          shiny::validate(       demand(ext == "csv", "Incorrect file type"),       demand(required_columns %in% column_names, "Wrong file type")     )          file_contents        })      output$contents <- renderTable({     input_file()   })      information <- function(){     tibble(       X = seq_len(input$periods),       Y = interpol(input$periods,matrix(c(input$matrix1[1,ane],input$matrix1[1,2])))     )   }        output$plot<-renderPlot({plot(data(),type="l",xlab="Periods (10)", ylab="Interpolated Y values")})      observeEvent(input$file1,{     updateMatrixInput(session,                        inputId = "matrix1",                        value = matrix(as.matrix(input_file()),                                      ncol=ii,                                      dimnames = list("Interpolate",c("X","Y"))                               )     )                          })      output$download <- downloadHandler(     filename = function() {       paste("Inputs","csv",sep=".")     },     content = part(file) {       write.csv(input$matrix1, file,row.names=Simulated)     }   ) }  shinyApp(ui, server)                  

enter image description here

enter image description here

enter image description here

enter image description here

Now the resolved lawmaking:

          library(dplyr) library(shiny) library(shinyFeedback) library(shinyMatrix)  nms <- c("10", "Y") # < Matrix variable names (headers)  interpol <- function(a, b) { # < a = periods, b = matrix inputs   c <- rep(NA, a)   c[1] <- b[ane]   c[a] <- b[2]   c <- approx(seq_along(c)[!is.na(c)], c[!is.na(c)], seq_along(c))$y    return(c) }  ui <- fluidPage(   useShinyFeedback(),   sidebarLayout(     sidebarPanel(       fileInput("file", "Optionally choose input file (csv)", take = ".csv"),       sliderInput('periods', 'Periods to interpolate over:', min=1, max=10, value=10),       matrixInput("matrix1",                    "Values to interpolate:",                   value = matrix(c(1,v),ncol = 2,dimnames = list(NULL,nms)),                   cols =  list(names = True),                   rows = list(names = Faux),                   class = "numeric"       ),       downloadButton("download")     ),     mainPanel(       tableOutput("contents"),       plotOutput("plot"),       verbatimTextOutput("verb")     )   ) )  server <- function(input, output, session) {   uploadData <- reactive({     req(input$file)     validate(need(identical(tools::file_ext(input$file$datapath),"csv"),"Invalid extension"))     attempt(read.csv(input$file$datapath, header = Truthful))   })      observeEvent(uploadData(), {     if(is.information.frame(uploadData()) &&         all(nms %in% names(uploadData())) &&         all(vapply(uploadData()[nms],is.numeric,NA))){           updateMatrixInput(session,"matrix1",as.matrix(uploadData()[nms]))           hideFeedback("file")         }      else {       showFeedbackWarning("file", "Invalid upload.")     }   })    data <- function(){     tibble(       X = seq_len(input$periods),       Y = interpol(input$periods,matrix(c(input$matrix1[1,1],input$matrix1[ane,2])))     )   }        output$plot<-renderPlot({plot(information(),type="l",xlab="Periods (X)", ylab="Interpolated Y values")})   output$verb <- renderPrint(class(uploadData()))        output$download <- downloadHandler(     filename = role() {       paste("Inputs","csv",sep=".")     },     content = function(file) {       write.csv(input$matrix1, file,row.names=False)     }   ) }  shinyApp(ui, server)                  

shearerplithe.blogspot.com

Source: https://stackoverflow.com/questions/70045163/how-to-more-completely-validate-csv-file-when-uploading-to-shiny-app

0 Response to "Validate to Read Upload File in Shiny"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel