Reputation: 175
Here are the codes that I'm using:
library(data.table)
# Get a List of all files in directory named with a key word, say all `.csv` files
filenames <- list.files("D:/FILES/yahoo cvs", pattern="*.csv", full.names=TRUE)
# read and row bind all data sets
data <- rbindlist(lapply(filenames,fread))
It works very well, but I want to combine files with cbindlist. I just simply changed rbindlist to cbindlist and it didn't work. How can I do this?
File AAA
C1 C2
R1 10 20
R2 30 40
File BBB
C1 C2
R1 50 60
R2 80 70
Combined new file
AAA.C1 AAA.C2 BBB.C1 BBB.C2
R1 10 20 R1 50 60
R2 30 40 R2 80 70
Upvotes: 1
Views: 2625
Reputation: 389135
Instead of lapply
if you use sapply
with simplify = FALSE
it will attach the filenames to the column names when you cbind
.
data <- do.call(cbind, sapply(filenames,data.table::fread, simplify = FALSE))
Upvotes: 4