2015-10-16 34 views
4

我有一個包含約700個文本文件的文件夾,我想要導入並添加一列。我已經想出瞭如何使用以下代碼執行此操作:如何在R中導入文本文件時跳過空文件?

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個文件是空的。因此代碼停止在第一個空文件和我得到這個錯誤消息:

錯誤函數read.table中(F,標題= F,九月=「」):可用 無線輸入

有沒有辦法跳過這些空文件?

謝謝!

+0

你知道如何檢查文件是否爲空?你可以添加一個if語句('if(file is not empty){do something}')。值得注意的是:如果您遇到性能問題,那麼有更高效的方法來做到這一點。多次調用rbind可能會很慢。 – Heroka

回答

1

對於不同的方法,引入明確的錯誤處理,想想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) 
} 
3

您可以通過檢查file.size(some_file) > 0跳過空文件:

files <- list.files("~/tmp/tmpdir", pattern = "*.csv") 
## 
df_list <- lapply(files, function(x) { 
    if (!file.size(x) == 0) { 
     read.csv(x) 
    } 
}) 
## 
R> dim(do.call("rbind", df_list)) 
#[1] 50 2 

這跳過了10個文件是空的,並且在沒有其他10讀取。


數據:

for (i in 1:10) { 
    df <- data.frame(x = 1:5, y = 6:10) 
    write.csv(df, sprintf("~/tmp/tmpdir/file%i.csv", i), row.names = FALSE) 
    ## empty file 
    system(sprintf("touch ~/tmp/tmpdir/emptyfile%i.csv", i)) 
}