更新时间:2022-10-16 09:43:16
对于引入显式错误处理的不同方法, $ c> tryCatch 来处理在你的 read.table
中可能发生的任何错误。
for(f in files){
data if(file。 size(f)> 0){
read.table(f,header = F,sep =,)
}
},error = function(err){
#错误处理程序拾取发生错误的位置
print(paste(Read.table does not work!:,err))
})
data $ species< - strsplit (f,split =c.txt)
DF }
I have a folder with about 700 text files that I want to import and add a column to. I've figured out how to do this using the following code:
files = list.files(pattern = "*c.txt")
DF <- NULL
for (f in files) {
data <- read.table(f, header = F, sep=",")
data$species <- strsplit(f, split = "c.txt") <-- (column name is filename)
DF <- rbind(DF, data)
}
write.xlsx(DF,"B:/trends.xlsx")
Problem is, there are about 100 files that are empty. so the code stops at the first empty file and I get this error message:
Error in read.table(f, header = F, sep = ",") : no lines available in input
Is there a way to skip over these empty files?
Thanks!
For a different approach that introduces explicit error handling, think about a tryCatch
to handle anything else bad that might happen in your read.table
.
for (f in files) {
data <- tryCatch({
if (file.size(f) > 0){
read.table(f, header = F, sep=",")
}
}, error = function(err) {
# error handler picks up where error was generated
print(paste("Read.table didn't work!: ",err))
})
data$species <- strsplit(f, split = "c.txt")
DF <- rbind(DF, data)
}