【问题标题】:r Reading multiple .text files and Error : more columns than column namesr 读取多个 .text 文件和错误:列多于列名
【发布时间】:2019-07-03 08:56:41
【问题描述】:

我正在尝试根据下面的脚本读取近 30000 个管道 (|) 分隔的文本文件

   mypath = "path/to/my/text/files/directory"
   setwd(mypath)

  # Create list of text files
  txt_files_ls = list.files(path=mypath, pattern="*.txt") 


  # Read the files in, assuming comma separator
  txt_files_df <- lapply(txt_files_ls, function(x) {read.table(file = x, header = T, sep ="|")})

  # Combine them
  Combined_df <- do.call("rbind", lapply(txt_files_df, as.data.frame))

我收到一个错误

Error in read.table(file = x, header = T, sep = "|") : 
  more columns than column names
In addition: There were 37 warnings (use warnings() to see them)

我的文件夹中有 30000 个文本文件,实际上不可能打开每个文件并检查哪个文件的列数超过预期。

如果有人可以帮助我解决此错误,那将会很有帮助。提前致谢。

【问题讨论】:

  • 使用for 循环而不是lapply。这样,当读取有问题的文件时,您会收到一个错误,您可以对其进行检查。
  • 尝试读取那些没有标题的文件。您始终可以在最后添加标题
  • 还可以在尝试后立即运行warnings(),这可能会为您提供有关正在发生的事情的进一步提示

标签: r import lapply rbind read.table


【解决方案1】:

您的数据中的某些文本字段很可能包含 |,而 read.table() 与分隔符混淆

尝试使用更强大的data.table::fread() 代替read.table()

library(data.table)

fread("filename.csv")

【讨论】:

    猜你喜欢
    • 2014-11-04
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2021-12-15
    相关资源
    最近更新 更多