【问题标题】:R - Loop through directory throws error but I do not know where (try and catch)R - 遍历目录会引发错误,但我不知道在哪里(尝试并捕获)
【发布时间】:2019-01-15 11:00:02
【问题描述】:

我有一个循环,它应该获取所有符合提供的正则表达式的文件。 但是,某些文件的所有行中的列数显然不正确。因此,循环崩溃。 我现在确实想找出导致这些错误的文件。有 100 多个文件,但只有少数会导致此错误。 我从 Java 知道,我现在会尝试创建一个 try-catch 子句并打印文件的名称以便找到它们,查看并删除/更改它们。我无法在 R 中处理这个问题:

#PATH WITH ALL FILES
files <- list.files(path="/Users/Test/Trackingpoint", 
pattern="Trackingpoint.*\\.csv\\.gz", full.names=TRUE, recursive=FALSE)

Trackingpoint_Tables <- 
  tryCatch({
    lapply(files, function(x) {
      a <- read.table(gzfile(x), sep = "\t", header = TRUE)
    })
  }, warning = function(w) {
    print(w)
  }, error = function(e) {
    print(e)  
    })

如您所知,我在 w 和 e 中拥有的不是文件本身,而是错误。如何打印文件名以及文件本身的任何其他信息? 我希望我的代码忽略错误并继续,但要告诉我,这个错误发生在哪里(哪个文件)。 现在,它只说:

<simpleError in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,     nmax = nrows, skip = 0, na.strings = na.strings, quiet = TRUE,     fill = fill, strip.white = strip.white, blank.lines.skip = blank.lines.skip,     multi.line = FALSE, comment.char = comment.char, allowEscapes = allowEscapes,     flush = flush, encoding = encoding, skipNul = skipNul): line 24610 did not have 44 elements>

【问题讨论】:

    标签: r loops try-catch


    【解决方案1】:

    read.tableread.csvfill=TRUE 的简单更改就足够了。

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-21
      • 1970-01-01
      • 2023-03-10
      • 2022-08-02
      • 2017-05-10
      相关资源
      最近更新 更多