忽略 readr::read_csv 中的尾随分隔符

Ignore trailing delimiters in readr::read_csv

当我使用 readr::read_csv 读取包含尾随定界符的 CSV 文件时,我收到一条警告,指出已填写缺少的列名称。这是一个简短的 CSV 文件示例的内容,用于重现此警告(将以下代码片段存储在名为 example.csv) 的文件中:

A,B,C,
2,1,1,
14,22,5,
9,-4,8,
17,9,-3,

注意每行末尾的逗号。现在,如果我用

加载这个文件
read_csv("example.csv")

我收到以下警告:

Missing column names filled in: 'X4'

即使我只想显式加载 3 列

read_csv("example.csv", col_types=cols_only(A=col_integer(),
                                            B=col_integer(),
                                            C=col_integer()))

我仍然收到警告消息。

这是预期的行为还是有某种方式告诉 read_csv 它应该忽略除我指定的列之外的所有列?或者是否有另一种方法来整理这个(显然格式错误的)CSV,以便尾随定界符是 deleted/ignored?

我认为你做不到。根据我在文档中看到的内容,cols_only() 适用于您已经加载的 R 对象。

但是,data.table 库中的 fread() 函数允许您在读入文件时 select 指定列名:

DT <- fread("filename.csv", select = c("colA","colB"))

这是另一个带有错误消息的示例。

> read_csv("1,2,3\n4,5,6", col_names = c("x", "y"))
Warning: 2 parsing failures.
row # A tibble: 2 x 5 col     row   col  expected    actual         file expected   <int> <chr>     <chr>     <chr>        <chr> actual 1     1  <NA> 2 columns 3 columns literal data file 2     2  <NA> 2 columns 3 columns literal data

# A tibble: 2 x 2
      x     y
  <int> <int>
1     1     2
2     4     5

这里是fix/hack。另请参阅此 SOF link。

> suppressWarnings(read_csv("1,2,3\n4,5,6", col_names = c("x", "y")))
# A tibble: 2 x 2
      x     y
  <int> <int>
1     1     2
2     4     5