如何跳过阅读 readr 中的某些列

how to skip reading certain columns in readr

我有一个名为 "test.csv" 的简单 csv 文件,其中包含以下内容:

colA,colB,colC
1,"x",12
2,"y",34
3,"z",56

假设我想跳过在 colA 中的读取,而只在 colB 和 colC 中读取。我想要一个通用的方法来执行此操作,因为我有很多文件要读入,有时 colA 完全称为其他名称,但 colB 和 colC 始终相同。

根据 read_csv 文档,实现此目的的一种方法是为 col_types 传递一个命名列表,并仅命名您要保留的列:

read_csv('test.csv', col_types = list(colB = col_character(), colC = col_numeric()))

通过不提及 colA,它应该从输出中删除。但是,生成的数据框是:

Source: local data frame [3 x 3]

      colA colB colC
    1    1    x   12
    2    2    y   34
    3    3    z   56

是我做错了什么还是 read_csv 文档不正确?根据帮助文件:

If a list, it must contain one "collector" for each column. If you only want to read a subset of the columns, you can use a named list (where the names give the column names). If a column is not mentioned by name, it will not be included in the output.

那里有答案,我只是没有努力搜索: https://github.com/hadley/readr/issues/132

显然这是一个已更正的文档问题。此功能最终可能会被添加,但 Hadley 认为仅更新一种列类型而不删除其他列类型更有用。

更新:已添加功能

以下代码来自readr documentation:

read_csv("iris.csv", col_types = cols_only( Species = col_factor(c("setosa", "versicolor", "virginica"))))

这将只读取鸢尾花数据集的 Species 列。为了只读取特定的列,您还必须传递列规范,即 col_factorcol_double 等...

"According to the read_csv documentation, one way to accomplish this is to pass a named list for col_types and only name the columns you want to keep"

WRONG: read_csv('test.csv', col_types=list(colB='c', colC='c'))

不,该文档具有误导性,您必须指定删除未命名的列 (class='_'/col_skip()),或者明确指定它们的 class 为 NULL:

read_csv('test.csv', col_types=list('*'='_', colB='c', colC='c'))

read_csv('test.csv', col_types=list('colA'='_', colB='c', colC='c'))