Shiny validate for read.csv - r

I am trying to use shiny validate function to capture reading errors and show customized error message when reading uploaded csv files instead of letting shiny forward the default read.csv error message.
Here is the simple code
validate(need(try(sd <- read.csv(file = sdFile[1], stringsAsFactors = FALSE)), "Error reading the file"))
when there is no format issue in the csv file, the code works normally. But when there is an issue with the csv file, the code still returns the default error message (in red font), eg., Error: undefined columns selected, but not the customized message. Any issue here? Thanks!

I think it is actually printing it out, if I do this:
library(shiny)
validate(need(try(sd <- read.csv(file = "mtcars1.csv",
stringsAsFactors = FALSE)),
Error reading the file !!!"))
yielding:
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'mtcars1.csv': No such file or directory
Error: Error reading the file !!!
I get this - note your message is the in the last line.
You can suppress the warnings with supressWarnings like this:
library(shiny)
suppressWarnings(
+ validate(need(try(sd <- read.csv(file = "mtcars1.csv",
stringsAsFactors = FALSE)),
"Error reading the file !!!!")))
yielding:
Error in file(file, "rt") : cannot open the connection
Error: Error reading the file !!!!
Or you can supress everything but your message with this (uses tryCatch instead of try):
library(shiny)
suppressWarnings(
validate(need(tryCatch(sd <- read.csv(file = "mtcars1.csv",
stringsAsFactors = FALSE), error=function (e){}),
"Error reading the file !!!!")))
yielding
Error: Error reading the file !!!

Related

RShiny: Pass in a FilePath

Trying to do something pretty simple here.. I just want to hard code a file path and pass it into "read.csv" but on run it's removing the "\t" from the string.
filePath = toString("C:\test.csv")
scenario_data <<- read.csv(filePath, stringsAsFactors=F)
Error:
Warning in file(file, "rt") :
cannot open file 'C: est.csv': Invalid argument
Warning: Error in file: cannot open the connection
1: runApp
I know in Python I can use r"this is a string" so that this doesn't happen. Is there something similar in RShiny?

Import Excel data into R using openxlsx: Error in file(con, "r") : invalid 'description' argument

I am trying to import the data in my Excel file into R using Openxlsx library:
library(openxlsx)
data <- read.xlsx("datafile.xlsx", sheet = "Sheet1")
However, I get the following error:
Error in file(con, "r") : invalid 'description' argument
In addition: Warning message:
In unzip(xlsxFile, exdir = xmlDir) : error 1 in extracting from zip file
This error is thrown because your Excel file is open.
Save and close the Excel file and try again, it will work.
There's also another possibility: the XLSX file could be password protected. If you delete the password, then this can fix the error.
I think the best way to solve this problem is to reset the pathway of your data source. Please do not include any characters without English in your pathway.
setwd("C:\\Users\\your path way (where you store datafile.xlsx)")
P.S.
Rstudio2021 seem not friendly to non-English user ☺☺☺

How do I use strings in functions for R ? (file,rt error)

I am trying to load data into a function to use for analysis later on and there seems to be issues inserting a string (i.e. a filename) into my function. Here is what I am working with.
hist_sep<- function(dex_file,etoh_file,sep_parameter) {
dex<-read.csv("dex_file")$sep_parameter
etoh<-read.csv("etoh_file")$sep_parameter
}
The code below outputs this error
hist_sep(RT_3h_Amp_A.csv , RT_3h_Amp_EtOH_A.csv , FL1.A)
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
However, if I input the filenames myself (as below) then everything works great. So everything is in the correct directory.
dex<-read.csv("RT_3h_Amp_A.csv")$FL1.A
etoh<-read.csv("RT_3h_Amp_EtOH_A.csv")$FL1.A
Any ideas how I could get around this problem?
Remove the quotes around the filenames in your function (e.g., should be dex<-read.csv(dex_file)$sep_parameter, not dex<-read.csv("dex_file")$sep_parameter). Otherwise, it's trying to download a file CALLED "dex_file".

Cannot read data from an xlsx file in RStudio

I have installed the required packages - gdata and ggplot2 and I have installed perl.
library(gdata)
library(ggplot2)
# Read the data from the excel spreadsheet
df = data.frame(read.xls ("AssignmentData.xlsx", sheet = "Data", header = TRUE, perl = "C:\\Strawberry\\perl\\bin\\perl.exe"))
However when I run this I get the following error:
Error in xls2sep(xls, sheet, verbose = verbose, ..., method = method, :
Intermediate file 'C:\Users\CLAIRE~1\AppData\Local\Temp\RtmpE3UYWA\file8983d8e1efc.csv' missing!
In addition: Warning message:
running command '"C:\STRAWB~1\perl\bin\perl.exe" "C:/Users/Claire1992/Documents/R/win-library/3.1/gdata/perl/xls2csv.pl" "AssignmentData.xlsx" "C:\Users\CLAIRE~1\AppData\Local\Temp\RtmpE3UYWA\file8983d8e1efc.csv" "Data"' had status 2
Error in file.exists(tfn) : invalid 'file' argument
Thanks to #Stibu I realised I had to set my work directory. This is the command you use to run in Rstudio; setwd("C/Documents..."). The file path is where the excel file is located.
I had the issue but I solved it differently.
My problem was because my file was saved as Excel (extension .xls) but it was a txt file.
I corrected the file and I did not meet any other error with the R function.

How to elegantly handle errors in R when state needs to be cleaned up?

What is the best was to handle errors in R? I want to be able to both abstract away stack traces from the end user of my script, as well as clean up any temporary variables and state i may be working with.
So i suppose my question is two fold:
Most importantly, how do i properly handle cleaning up state when handling errors?
How do i extract, useful, nice information from R's error messages, without internal
stuff being spit out?
At the moment, I have something which looks like this, but (1) it seems horribly inelegant, and (2) still gives me horrible error messages.
# Create some temporary working state and variables to clean up
file <- "somefile"
working.dir <- getwd()
setwd("../") # Go somewhere else
saf.default <- getOption("stringsAsFactors")
options(stringsAsFactors = FALSE)
# Now lets try to open the file, but it doesn't work (for whatever reason)
# I want to clean up the state, stop, and wrap the error string with a nicer
# message
tryCatch({
# Need to embed the tryCatch because we still need some of the state variables
# for the error message
tryCatch({
f <- read.table(file)
}, error = function(err.msg) {
# Can't clean up here, we still need the `file variable!
stop("Could not open file '", file, "' with error message:\n", print(err.msg),
call.=FALSE)
})
}, error = function(err.msg) {
# Now we can clean up state
setwd(working.dir)
options(stringsAsFactors = saf.default)
rm(file, working.dir, saf.default,
envir=globalenv()) # This also seems awful?
stop(print(err.msg), call.=FALSE)
})
# Do more stuff, get more state, handle errors, then clean up.
# I.e can't use `finally` in previous tryCatch!
The error message from this comes out as, still lots of ugly internals:
# <simpleError in file(file, "rt"): cannot open the connection>
# <simpleError: Could not open file 'somefile' with error message:
# Error in file(file, "rt"): cannot open the connection
>
# Error: Could not open file 'somefile' with error message:
# Error in file(file, "rt"): cannot open the connection
# In addition: Warning messages:
# 1: In file(file, "rt") :
# cannot open file 'somefile': No such file or directory
# 2: In stop(print(err.msg), call. = FALSE) :
# additional arguments ignored in stop()
>
I would isolate any state-changing code into its own function, and use on.exit. This guarantees that cleanup will happen, no matter if an error occurs.
readFile <- function(.....)
{
on.exit({
setwd(cur.dir)
options(stringsAsFactors=saf)
})
cur.dir <- getwd()
saf <- getOption("stringsAsFactors")
setwd("new/dir")
options(stringsAsFactors=FALSE)
....
}

Resources