Possible Duplicate:
When importing CSV into R how to generate column with name of the CSV?
I got a collection of files that I want to load into a single data frame. Each of the files I’m reading has the same structure, but different number of rows. Let’s say that each of those files represent a single participant, and I know I can read them using the code below:
files <- c("john.csv","fred.csv","nick.csv","alex.csv")
library(plyr)
dfoc <- ldply(files, read.csv, header = T)
Now, I want to be able to identify which rows belong to which participant. I want to add a single column for each of those files before I read them into a big data frame. The column I want to add will have a number of rows equal to number of rows for specific participant nrow(john). The column I add should simply contain an identifier, for example file name repeated nrow(x) times.
Any suggestions?
Here is what I’d do. (The key idea is to place the value of the
idcolumn and the just-read-in data.frame together inside a call todata.frame(). R’s recycling rules will make theidcolumn have the right length in each case.)