【问题标题】:Read multiple csv files (and skip 2 columns in each csv file) into one dataframe in R?将多个csv文件(并在每个csv文件中跳过2列)读入R中的一个数据帧?
【发布时间】:2020-01-01 00:10:52
【问题描述】:

我有一个包含大约 100 个 csv 文件的文件夹,我想将它们读入 R 中的一个数据框中。我知道如何执行此操作,但我必须跳过每个 csv 文件中的前两列,这就是其中的一部分我被困住了。 到目前为止我的代码是:

myfiles <- list.files(pattern = ".csv") # create a list of all csv files in the directory
data_csv <- ldply(myfiles, read.csv)

感谢您的帮助

【问题讨论】:

标签: r


【解决方案1】:

使用 data.table 包函数 fread()rbindlist() 将提供比任何其他 basetidyverse 替代方案更快的结果。

library(data.table)

## Create a list of the files
FileList <- list.files(pattern = ".csv")

## Pre-allocate a list to store all of the results of reading
## so that we aren't re-copying the list for each iteration
DTList <- vector(mode = "list", length = length(FileList))

## Read in all the files, excluding the first two columns
for(i %in% seq_along(DTList)) {
  DTList[[i]] <- data.table::fread(FileList[[i]], drop = c(1,2))
}

## Combine the results into a single data.table
DT <- data.table::rbindlist(DTList)

## Optionally, convert the data.table to a data.frame to match requested result
## Though I would recommend looking into using data.table instead!
data.table::setDF(DT)

【讨论】:

    【解决方案2】:

    这是使用 purrr 的一种方法。您可以使用基本 lapply 函数执行基本相同的语法。下面使用的map_dfr 函数使用矢量化应用read.csvfread。它还有一个很好的特性,可以同时将数据帧(按行)绑定在一起,为您提供一个数据帧。

    library(purrr)
    myfiles <- list.files(pattern = ".csv") # create a list of all csv files in the directory
    data_csv <- map_dfr(myfiles, ~read.csv(.x)[,-c(1,2)])
    

    从 Matt 的回答中记下,您可以使用 fread 和矢量化更快:

    myfiles <- list.files(pattern = ".csv") # create a list of all csv files in the directory
    data_csv <- map_dfr(myfiles, ~data.table::fread(.x, drop = c(1,2))
    

    如果你想真的快点,你总是可以与furrr 包并行。

    library(purrr)
    library(furrr)
    
    # sets up the workers
    plan("multisession")
    
    myfiles <- list.files(pattern = ".csv") # create a list of all csv files in the directory
    data_csv <- future_map_dfr(myfiles, ~data.table::fread(.x, drop = c(1,2))
    
    

    【讨论】:

      猜你喜欢
      • 2016-06-14
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 2011-07-16
      • 2014-12-29
      • 1970-01-01
      相关资源
      最近更新 更多