将大量.txt文件导入data.frame,通过为其提供行data.frame包含空的.txt文件

时间:2016-10-25 15:58:13

标签: r

我有大量的.txt文件,我尝试在R中导入。有些.txt文件是空的,但我仍然想要包含在我的data.frame中.txt文件具体是空。使用以下函数,我可以将所有必需的.txt文件导入列表:

file_list <- list.files()
myList <- lapply(file_list, function(x) {tryCatch(read.table(x, header = F, sep = '|'), error=function(e) NULL)})

但是,当我使用以下代码将此列表更改为data.frame时:

myDataframe <- rbind.fill(lapply(myList, function(f) {as.data.frame(Filter(Negate(is.null), f))}))

我丢失了哪些.txt文件为空的信息。

最终,我希望在每一行中添加一个列,其中包含.txt文件的名称,例如通过list.files()。通过这种方式,我可以看到哪些行是空的。

1 个答案:

答案 0 :(得分:1)

这是解决您问题的方法,但不是您问题的具体答案。

取决于文本文件的大小。您应该考虑切换到data.table。一个非常好的系统,可以快速,高效地处理大型文件。

install.packages("data.table")
library(data.table)
file_list <- list.files()

Results <-  NULL
for (i in file_list){
  # data.table command to read txt files
  i.file <- tryCatch(fread(i,colClasses="character"), error=function(e) e)

  if(!class(i.file)[1]=="data.table"){
    # This condition checks that no errors occured
    i.file <- data.table(cbind(txt.file=i,is.empty="YES",
                         message=i.file$message))
  } else if(nrow(i.file)==0){
    # Just in case files are still empty even though no error
    i.file <- data.table(cbind(txt.file=i,is.empty="YES",
                         message=NA))
  } else {
    i.file[,txt.file:=i]
    i.file[,is.empty:="No"]
  }
  Results <- rbind(Results,i.file,fill=TRUE)
  rm(i.file);gc()
}

# to find which files are empty
Results[is.empty=="YES"][,txt.file]
# double check error types
Results[is.na(message)][,message] 
# expect all to be something like 'file is empty'

# if you insist on using data.frames
Results <- data.frame(Results)

这对你有用。该脚本可以转换为与lapply一起使用的函数,但我希望它易于理解和概括。

此外,我是data.table的忠实粉丝,过渡到它真的对我有帮助。有关该软件包的更多信息,请查看此cheatsheet

编辑:脚本已修改,因此可以容纳带有空格的空文件