将多个.csv文件合并为一个 [英] Merge multiple .csv files into one

查看:273
本文介绍了将多个.csv文件合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am aware this question has been asked multiple times, but despite of trying to apply the aforementioned solutions i was not able to solve my little problem:

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

I have saved all my .csv that i am aiming to merge into one folder:

> 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"  

我使用do.call tio将它们全部合并.请注意,所有文件都具有相同的格式.

the I use a do.call tio merge them all. Note that all the files have the same format.

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

但是,在检查完生成的文件后,我意识到只有第一个文件已导入. 是什么原因导致此问题?

however after inspecting my resulting file I have realized that only the first file has been imported. What causes this problem?

> str(sr.master)
'data.frame':   1941 obs. of  8 variables:
 $ Berechnung: Factor w/ 51 levels "Berechnung 1",..: 51 1 12 23 34 45 47 48 49 50 ...
 $ Situation : Factor w/ 13 levels "Nach Massnahme 0",..: 6 6 6 6 6 6 6 6 6 6 ...
 $ Sachrisiko: num  1857 1857 1857 1337 1342 ...
 $ PID       : int  2844 2844 2844 2844 2844 2844 2844 2844 2844 2844 ...
 $ Case      : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Differenz : num  0 0 0 -28 -27.7 ...
 $ Prozess   : Factor w/ 1 level "Murgang": 1 1 1 1 1 1 1 1 1 1 ...
 $ Objektart : Factor w/ 1 level "Einfamilienhaus": 1 1 1 1 1 1 1 1 1 1 ...

推荐答案

这是一种简单的方法(可能是最快的方法),它使用fread{data.table} 读取并将多个.csv文件绑定到一个数据帧中

Here is a simple way (and probably the fastest one) to read andbind multiple .csv files into one single data frame using 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))

如果要将所有数据文件绑定到数据帧列表中,就这么简单

And in case you want to bind all data files into a list of data frames, it's as simple as

# Load data sets
  list.DFs <- lapply(filenames,fread)

这篇关于将多个.csv文件合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆