Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to merge multiple csv files in R

Tags:

import

r

csv

I'm attempting to merge multiple csv files using R. all of the CSV files have the same fields and are all a shared folder only containing these CSV files. I've attempted to do it using the following code:

multmerge=function(mypath) {
    filenames=list.files(path=mypath, full.names=TRUE)
    datalist= lapply(filenames, function (x) read.csv(file=x, header=True))
    Reduce(function(x,y) merge(x,y), datalist)}

I am entering my path as something like "Y:/R Practice/specdata". I do get an ouput when I apply the function to my 300 or so csv files, but the result gives me my columns names, but beneath it has <0 rows> (or 0-length row.names). Please let me know if you have any suggestions on why this isn't working and how I can fix it.

like image 272
Cole Avatar asked May 14 '15 16:05

Cole


2 Answers

For a shorter, faster solution

library(dplyr)
library(readr)
df <- list.files(path="yourpath", full.names = TRUE) %>% 
  lapply(read_csv) %>% 
  bind_rows 
like image 148
Maiasaura Avatar answered Oct 14 '22 00:10

Maiasaura


Your code worked for me, but you need change header = True to header = TRUE.

like image 45
Matt Upson Avatar answered Oct 14 '22 00:10

Matt Upson