在R中导入文本文件时如何跳过空文件? [英] How to skip empty files when importing text files in R?
问题描述
我有一个包含大约700个文本文件的文件夹,我想导入并添加一列。我已经想出了如何使用下面的代码:
files = list.files(pattern =* c。 (f in file){
data< - read.table(f,header = F,sep =,)$ b $($)
DF < - NULL
(列名是文件名)
DF < - rbind(DF,data)
}
write.xlsx(DF,B:/trends.xlsx)
问题是,大约有100个文件是空的。所以代码停在第一个空文件,我得到这个错误信息:
read.table(f,header = F,sep =, ):
输入中没有可用的行
有没有办法跳过这些空文件?
谢谢!
对于引入显式错误处理的不同方法, $ c> tryCatch 来处理在你的 read.table
中可能发生的任何错误。
for(f in files){
data < - tryCatch({
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 < - rbind(DF,data)
}
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)
}
这篇关于在R中导入文本文件时如何跳过空文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!