我有一个包含.txt文件的.zip格式的令人难以置信的原始数据。在大多数情况下,它使用read_csv干净利落地读入数据,但在某些行中,数据记录了其他内容,并完全扭曲了列结构。这些数据不可能是固定的。
在使用read_csv时,它表现为一个解析问题。我想设置我的代码,如果这个问题出现在数据中,整个文件都会被忽略。如果有哪些文件被忽略/丢弃的日志,那就太好了。我查看了possibly(),但由于它不是文件的完整错误,只有行错误,所以它没有跳过文件。
这是我目前的代码。
library(dplyr)
library(readr)
library(purrr)
read_log <- function(path) {
read_csv(path, col_types = cols(.default = col_character())) %>%
mutate(filename = basename(path))
}
test_files <- file.path("example.txt") #would normally be list.files, simplified for this reprex
raw_data <- map_dfr(test_files, read_log)
#> Warning: 6 parsing failures.
#> row col expected actual file
#> 3 -- 17 columns 4 columns 'example.txt'
#> 4 -- 17 columns 23 columns 'example.txt'
#> 5 -- 17 columns 23 columns 'example.txt'
#> 6 -- 17 columns 23 columns 'example.txt'
#> 7 -- 17 columns 23 columns 'example.txt'
#> ... ... .......... .......... .............
#> See problems(...) for more details.发布于 2020-07-02 11:12:18
如果返回警告,可以返回NULL。尝试使用此函数。
library(reader)
library(purrr)
library(dplyr)
read_log <- function(path) {
data <- tryCatch(read_csv(path,col_types = cols(.default = col_character())),
warning = function(e) return(NULL))
if(!is.null(data))
data <- data %>% mutate(filename = basename(path))
return(data)
}使用map而不是map_dfr读取数据:
all_data <- map(test_files, read_log)未读取的文件
not_read_files <- test_files[sapply(all_data, is.null)]合并数据
total_data <- bind_rows(all_data)https://stackoverflow.com/questions/62687626
复制相似问题