合并多个的.csv文件合并成一个
问题描述:
我知道这个问题已经被问多次,但尽管尝试应用上述解决方案,我没能解决我的小问题:合并多个的.csv文件合并成一个
我救了我的所有。 CSV是我的目标合并成一个文件夹:
> 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
蒂奥合并他们。请注意,所有文件都具有相同的格式。
sr.master <- do.call("rbind", lapply(file_list, read.csv, sep = ";", header = TRUE))
names(sr.master)
str(sr.master)
然而,在检查我的结果文件后,我意识到只有第一个文件已被导入。 导致此问题的原因是什么?
> 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 ...
答
# 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)
答
这里有一个简单的方法(和probbly最快的国家之一)使用fread{data.table}
# Load library
library(data.table)
# Get a List of all files named with a key word, say all `.csv` files
filenames <- list.files("C:/your/folder", pattern="*.csv", full.names=TRUE)
# Load and bind all data sets
data <- rbindlist(lapply(filenames,fread))
而且在你想要的情况下绑定多个.csv
文件帧到一个单一的数据帧将所有数据文件绑定到数据帧列表中,就像
# Load data sets
list.DFs <- lapply(filenames,fread)
没有一个工作示例,诊断相当困难。我建议你最初将'do.call(.. lapply ...)'分成两个独立的步骤。首先,像'myData lmo
当你只运行'lapply(file_list,read.csv,sep =“;”,header = TRUE)时, ? – Jimbou
@Jimbou,'sep =“,”'对于csv文件不是';' – parth