【问题标题】:Read CSV in R and filter columns by name在 R 中读取 CSV 并按名称过滤列
【发布时间】:2019-07-03 19:25:21
【问题描述】:

假设我有一个包含数十或数百列的 CSV,并且我只想提取大约 2 或 3 列。我知道here 描述的colClasses 解决方案,但代码变得非常不可读。

我想要来自pandas' read_csv 的类似usecols 的东西。

加载所有内容然后再选择不是解决方案(文件超级大,它不适合内存)。

【问题讨论】:

    标签: r csv readr


    【解决方案1】:

    一种方法是使用包sqldf。如果您了解 SQL,则可以读取大文件,仅过滤您想要的部分。

    我将使用内置数据集iris 使示例可重现,首先将其保存到磁盘。

    write.csv(iris, "iris.csv", row.names = FALSE)
    

    现在是问题。
    参数row.names 就像在write.csv 指令中一样。
    注意Sepal.Length 周围的反引号。这是由于列名中的点字符造成的。

    library(sqldf)
    
    sql <- "select `Sepal.Length`, Species from file"
    sub_iris <- read.csv.sql("iris.csv", sql = sql, row.names = FALSE)
    
    head(sub_iris)
    #  Sepal.Length  Species
    #1          5.1 "setosa"
    #2          4.9 "setosa"
    #3          4.7 "setosa"
    #4          4.6 "setosa"
    #5          5.0 "setosa"
    #6          5.4 "setosa"
    

    最后清理。

    unlink("iris.csv")
    

    【讨论】:

      【解决方案2】:

      我将使用包data.table,然后使用fread() 指定要保留/删除的列,并通过参数selectdrop。来自?fread

      选择要保留的列名称或数字的向量,删除其余部分。

      drop 要删除的列名或数字的向量,保留其余部分。

      最好的!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-20
        • 2020-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-08
        相关资源
        最近更新 更多