【问题标题】:Ignore trailing delimiters in readr::read_csv忽略 readr::read_csv 中的尾随分隔符
【发布时间】:2017-05-07 21:51:22
【问题描述】:

当我使用 readr::read_csv 读取包含尾随分隔符的 CSV 文件时,我收到一条警告,指出填写了缺少的列名。这是一个简短示例 CSV 文件的内容,用于重现此警告(存储以下 sn -p 在一个名为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,以便删除/忽略尾随分隔符?

【问题讨论】:

  • 你能添加一个显示问题的小例子吗?警告会以某种方式影响输出还是只是一条消息?
  • 这只是一条警告消息,但即使使用cols_only 所有列似乎都已导入,这似乎很奇怪。我编辑了我的问题以包含一个小的示例 CSV 文件来显示问题。

标签: r csv readr tidyverse


【解决方案1】:

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

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

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

【讨论】:

    【解决方案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 链接。 Suppress reader parse problems in 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
    

    【讨论】:

    • 这个blog post 描述了如何只捕获特定的警告。仅禁止显示此特定警告可能很有用。
    猜你喜欢
    • 2020-12-30
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 2016-06-05
    • 2018-03-25
    相关资源
    最近更新 更多