[R] Run script automatically on several input files in the directory and produce separate outputs?

MacQueen, Don macqueen1 at llnl.gov
Fri Dec 5 20:07:17 CET 2014

The simplest approach, and a good one for someone new to R, would be
something like this:

myfiles <- c('fileA', 'fileB','fileC")

for (nm in myfiles) {
  cat('now reading input file',nm,'\n')
  mydat <- read.table( paste0(nm,'.txt'), header=TRUE)
  pdf( paste0(nm, '.pdf') )
  plot(etc , main=nm)

I stored the file names without the ".txt", so that the base part of the
name could more easily be used to construct the pdf file name. The
paste0() command is used to construct the full input and pdf file names,
i.e., with the .txt and .pdf suffices.

Fancier tools include using functions like list.files() to, for example,
find the names of all the .txt files in your current working directory,
but until you understand what I've shown you, I wouldn't tackle those.

Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550

On 12/5/14, 5:40 AM, "Thomas Barningham" <stbarningham at gmail.com> wrote:

>I have written a script that currently reads in a .txt file where I
>specify the name e.g
>mydata<-read.table("a_date.txt", header=TRUE)
>The script eventually produces a plot, e.g:
>What I want to do is run this script on several input files in my
>directory, without having to manually change the input file name each
>time, and produce the output plot pdf with the input file name as the
>output file name. It would also be handy if my plot title is also the
>input file name.
>I'm relatively new to R so i'm not sure how to approach this. I
>presume it's some sort of loop function, but i've never implemented
>one of these before - any advice would be greatly appreciated!
>Thanks in advance!
>Thomas Barningham
>Centre for Ocean and Atmospheric Sciences
>School of Environmental Sciences
>University of East Anglia
>Norwich Research Park
>NR4 7TJ
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>PLEASE do read the posting guide
>and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list