Reputation: 175
I've tried several ways that are already discussed about this issue in stack overflow, but still can't do this. I have more than 10 cvs files in my computer. I want to combine (cbind) each file into one big data frame. And I want to have column names as a name of each file. Any ideas?
Upvotes: 2
Views: 92
Reputation: 73272
Just use read.csv
in an lapply
; when you cbind
afterwards, the names get attached as prefix to the column names. (List should be named of course.)
f.names <- c("file1.csv", "file2.csv", "file3.csv")
res <- do.call(cbind, setNames(lapply(f.names, read.csv), gsub("\\.csv$", "", f.names)))
res
# file1.a file1.b file1.c file1.d file2.a file2.b file2.c file2.d file3.a file3.b
# 1 1 4 7 10 1 4 7 10 1 4
# 2 2 5 8 11 2 5 8 11 2 5
# 3 3 6 9 12 3 6 9 12 3 6
# file3.c file3.d
# 1 7 10
# 2 8 11
# 3 9 12
Data:
df0 <- data.frame(matrix(1:12, 3, 4, dimnames=list(NULL, letters[1:4])))
sapply(1:3, function(i) write.csv(df0, file=sprintf("file%s.csv", i), row.names=FALSE))
Upvotes: 3