Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging multiple csv files in R using do.call

Tags:

merge

r

do.call

I am trying to import and merge a set of csv files using the following code, but it doesn't seem to be passing the by=c("X","Y") argument to the merge function. Any recommendations on how to fix this? Thank you

csvfiles <- list.files(path = ".", pattern='bbg_.*\\.csv$')
csvfiles <- paste("fx/",csvfiles,sep="")
csvfiles

my.df <- do.call("merge",list(lapply(csvfiles, read.csv, header = TRUE), by=c("date","fx_code")))
like image 602
ec0n0micus Avatar asked Mar 25 '14 19:03

ec0n0micus


People also ask

How can two CSV files be merge having names as common variable in R?

Load the two csv files into R. (Don't forget to make sure their common variables share the same name!). Merge the dataframes together by their shared variables and add argument all. x=T (the default) to ensure all rows are kept from your database containing species.

How are multiple datasets imported and combined simultaneously in R?

files(), lapply(), and bind_rows() from these packages and pass the required parameters to these functions to merge the given multiple CSV files to a single data frame in the R programming language.


1 Answers

merge doesn't accept more than 2 data.frames, so you can't pass it a larger list using do.call:

do.call(merge, list(iris, iris, iris))
#Error in fix.by(by.x, x) : 
#  'by' must specify one or more columns as numbers, names or logical

Use Reduce instead:

Reduce(function(x, y) merge(x, y, by="Species"), list(iris, iris, iris))
#works
like image 100
Roland Avatar answered Oct 21 '22 19:10

Roland