5

当我使用 读取包含尾随分隔符的 CSV 文件时readr::read_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,以便删除/忽略尾随分隔符?

4

2 回答 2

3

我不认为你可以。从我在文档中可以看到,cols_only()是针对您已经加载的 R 对象。

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

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

于 2016-12-22T10:07:49.430 回答
2

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

> 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

这是修复/破解。另请参阅此 SOF 链接。 抑制阅读器解析r中的问题

> 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
于 2017-08-21T20:45:57.590 回答