将多个.csv文件合并为一个

时间:2017-06-02 12:47:29

标签: r csv rbind read.csv do.call

我知道这个问题已被多次询问,但尽管尝试应用上述解决方案,但我无法解决我的小问题:

我保存了所有我想要合并到一个文件夹中的.csv:

#lang racket
(define  (true-for-all? pred list)
  (cond
    [(empty? list) #t]
    [(pred (first list)) (true-for-all? pred (rest list))]
    [else #f]))

我使用> file_list <- list.files() > file_list[] [1] "SR-einfam.csv" "SR-garage.csv" "SR-hotel.csv" [4] "SR-IndustrieGewerbe.csv" "SR-mehrfam.csv" "SR-OffG.csv" tio将它们全部合并。请注意,所有文件都具有相同的格式。

do.call

然而,在检查我的结果文件后,我意识到只导入了第一个文件。 导致此问题的原因是什么?

sr.master <- do.call("rbind", lapply(file_list, read.csv,  sep = ";", header = TRUE)) 
names(sr.master)
str(sr.master)

2 个答案:

答案 0 :(得分:4)

以下是使用.csv

将多个fread{data.table}文件读取并绑定到一个数据框中的简单方法(可能是最快的方法)
# Load library
  library(data.table)

# Get a List of all files in directory named with a key word, say all `.csv` files
  filenames <- list.files("C:/your/folder", pattern="*.csv", full.names=TRUE)

 # read and row bind all data sets
   data <- rbindlist(lapply(filenames,fread))

如果您想将所有数据文件绑定到数据框列表中,它就像

一样简单
# Load data sets
  list.DFs <- lapply(filenames,fread)

答案 1 :(得分:2)

# Get file list
  file_list <- list.files()

# Read all csv files in the folder and create a list of dataframes
  ldf <- lapply(file_list , read.csv)

# Combine each dataframe in the list into a single dataframe
  df.final <- do.call("rbind", ldf)