0

I am a student learning to program in R. This may be a simplistic question.

I have a file holding the absolute file path to my data files organized like this:

/path/to/my/datafile1
/path/to/my/datafile2
/path/to/my/datafile3
...

All the data in these files are formatted in the same way as the following

45 1
50 2
60 4
56 7
...

I would like to import, and feed these data files into one dataframe and add a label (the filename) noting where the data came from. The end dataframe should look like.

45 1 datafile1
50 2 datafile1
60 4 datafile1
56 7 datafile1
...

I cannot think of a way to efficiently do this without hardcoding every step. Is there a more efficient way of doing this?

Thanks

Nicholas Hayden
  • 473
  • 1
  • 3
  • 24

1 Answers1

1

See this documentation for detailed explanation:http://www.r-bloggers.com/merging-multiple-data-files-into-one-data-frame/

So, in your case:

multmerge = function(mypath){
filenames=list.files(path=mypath, full.names=TRUE)
datalist = lapply(filenames, function(x){read.csv(file=x,header=T)})
Reduce(function(x,y) {merge(x,y)}, datalist)
Claire
  • 135
  • 2
  • 11