Skip to content
Prev 388519 / 398513 Next

error message from read.csv in loop

Hello,

1. When there are systematic errors, use ?try or, better yet, ?tryCatch.
Something like the code below will create a list of errors and read in 
the data if none occurred.
The code starts by creating an empty list for tryCatch results. It uses 
?file.path instead of noquote/paste0 to assemble the file name and wraps 
tryCatch around read.csv. Then, after the for loop, it gets the wrong 
reads and displays the error messages.
3. I'm assuming that after processing the data file by file you discard 
the data.frame if it's read without problems and move on to the next 
one. It would also be possible to store them all in a list, together 
with the errors.


ok <- vector("list", nrow(ora))
for (j in 1:nrow(ora))
{
 ? mycol? <- ora[j,"fname"]
 ? mycsv? <- paste0(mycol, ".csv'")
 ? rdcsv? <- file.path("w:/project/_Joe.B/Oracle/data", mycsv)
 ? rr <- tryCatch(read.csv(rdcsv), error = function(e) e)
 ? if(inherits(rr, "error"))
 ??? ok[[i]] <- rr
 ? else ok[[i]] <- TRUE
}

i_err <- sapply(ok, inherits, "error")
for(e in ok[i_err]) message(e$message)


2. I'm assuming that you want to process file by file and? if the data 
are read without problems you discard the data.frame after processing it 
and move on to the next file. It is also possible to store them all in a 
list, together with the errors.


fun <- function(j, data = ora, mypath = "w:/project/_Joe.B/Oracle/data")
{
 ? mycol? <- data[j, "fname"]
 ? mycsv? <- paste0(mycol, ".csv")
 ? rdcsv? <- file.path(mypath, mycsv)
 ? tryCatch(read.csv(rdcsv), error = function(e) e)
}

df_list <- lapply(seq_len(nrow(ora)), fun)
i_err <- sapply(df_list, inherits, "error")
df_list[!i_err]? # these are ok

# hypothetical processing strategy
processing_results <- lapply(df_list[!i_err], function(rr) {
 ? # code goes here
 ? # ...etc...
})


Hope this helps,

Rui Barradas



?s 19:01 de 09/07/2021, Kai Yang via R-help escreveu: