merging multiple csv files in R using do.call
Asked Answered
R

2

15

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")))
Rundell answered 25/3, 2014 at 19:46 Comment(0)
C
38

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
Chalybite answered 25/3, 2014 at 19:57 Comment(1)
thanks very much - that worked. i used import.list <- lapply(csvfiles, read.csv, header = TRUE) my.df <- Reduce(function(x, y) merge(x, y, all=FALSE,by=c("fx_code","date"),all.x=TRUE, all.y=TRUE),import.list,accumulate=F)Rundell
B
3

do.call accepts a list of all arguments, so try:

my.df <- do.call("merge",append(lapply(csvfiles, read.csv, header = TRUE), list(by=c("date","fx_code")) )
Brout answered 25/3, 2014 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.