[R] R help: Batch read files based on names in a list

Enrico Schumann es at enricoschumann.net
Thu May 16 07:15:09 CEST 2013


On Wed, 15 May 2013, Jonathan Dry <dryjon at gmail.com> writes:

> *
>
> I am currently reading in a series of files, applying the same functions to
> them one at a time, and then merging the resulting data frames e.g.:
>
>>MyRows <- c("RowA", "RowB", "RowC")>>File1_DF <- read.delim("\\\\DirectoryToFiles\\File1_Folder\\File1.txt", stringsAsFactors=FALSE, check.names=FALSE)>File1_DF <- as.data.frame(t(File1_DF[MyRows,]))>File1_DF <- as.data.frame(t(File1_DF))>mergeDF <- merge(mergeDF,File1_DF, by.x = "Row.names", by.y="row.names")>>File2_DF <- read.delim("\\\\DirectoryToFiles\\File2_Folder\\File2.txt", stringsAsFactors=FALSE, check.names=FALSE)>File2_DF <- as.data.frame(t(File2_DF[MyRows,]))>File2_DF <- as.data.frame(t(File2_DF))>mergeDF <- merge(mergeDF,File2_DF, by.x = "Row.names", by.y="row.names")
>
> ...etc
>
> I want to know if I can use a list of the filenames c("File1", "File2",
> "File2") etc. and apply a function to do this in a more automated fasion?
> This would involve using the list value in the directory path to read in
> the file i.e.

Something like this?

  files <- dir("my_directory")
  for (f in files) {
      ## do something with file 'f'
  }



-- 
Enrico Schumann
Lucerne, Switzerland
http://enricoschumann.net



More information about the R-help mailing list