我有一个包含大约 700 个文本文件的文件夹,我想要导入并向其中添加一列。我已经想出了如何使用以下代码来做到这一点:
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")
问题是,大约有 100 个文件是空的。所以代码在第一个空文件处停止,我收到此错误消息:
Error in read.table(f, header = F, sep = ",") : no lines available in input
有没有办法跳过这些空文件?
最佳答案
对于引入显式错误处理的不同方法,请考虑使用 tryCatch
来处理 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 - 导入文本文件时跳过空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33175505/