r - readr read_fwf 奇怪的解析错误:embedded null
问题描述
我正在尝试用来readr::read_fwf
读入 .txt 文件。我知道所有的列宽,但我收到了这个解析错误,我不知道如何解决:
fwf_widths <- c(12, 2, 6, ...)
fwf_names <- c("V1", "V2", "V3", ...)
col_types <- c("ccc...")
df <- read_fwf(file = file, fwf_widths(fwf_widths, fwf_names),
col_types = col_types)
Warning: 1 parsing failure.
row col expected actual file
372722 description embedded null /path/to/my/file.txt
我试过添加trim_ws = T
哪个不能消除错误。我查看了实际内容,df[372722, ]
它看起来description
包含正确的内容。有人可以帮我解释什么 embedded null
意思以及我可以如何处理这个问题吗?
解决方案
fwf 中的一个字节是零值字节,这在 R 字符串中是非法的。如果只是将其删除,则会破坏 fwf 中后续条目的对齐方式,因此您需要替换它。默认情况下,以下函数将在任何零字节位置写入一个空格字符。
请在使用之前备份您的 .fwf 文件。
replace_null <- function(path_to_file, file_size = 10000000L, replace_with = ' ')
{
file_data <- readBin(path_to_file, "raw", file_size)
file_data[data == as.raw(0)] <- as.raw(as.numeric(charToRaw(replace_with)))
writeBin(file_data, path_to_file)
}
现在你只需要做
replace_null(file_path)
然后您自己的代码应该可以工作。如果没有,您的 fwf 必须已损坏。