[R] renaming an object

Prof Brian D Ripley ripley at stats.ox.ac.uk
Mon Oct 16 08:15:10 CEST 2000

On Mon, 16 Oct 2000, Natalie Roberts wrote:

> Say I have a file called exp.batch which contains 2 cols
> The first col contains names of R objects the user would like to use.
> The second col contains the file names which will be read in using
> read.table
> i.e. exp.batch may look like this.....
> name1	complex/filename/path1.txt
> name2   complex/filename/path2.txt
> name3	complex/filename/path3.txt
> name4   complex/filename/path4.txt
> I want to have a function which will read in the files and make them into
> the objects named in the 1st column - automatically (by just providing
> exp.batch)
> for(i in 1:nrow(exp.batch)){
> tmp<-read.table(as.name(exp.batch[i,2]),...)
> ##
> ##But now I really want tmp to be   as.name(exp.batch[i,1])???
> ## so that I can call the data from complex/filename/path1.txt
> ## by typing name1 
> }
> In  the end I should have objects name1, name2, name3, name4
> which are the names stored in the 1st column of exp.batch
> The basic idea is having to avoid typing out all this!
> name1<-read.table("file1",....)
> name2<-read.table("file2",....)
> ..
> ..
> ..
> nameN<-read.table("fileN",...)
> Does anyone have any suggestions?

You said exp.batch was a file and you treat it as a matrix/data frame,
so I will assume that if the first you have read it into the second
by, say,

exp.batch <- matrix(scan("exp.batch"), ncol=2, byrow=TRUE)

Then use

for(i in 1:nrow(exp.batch)) 
   assign(exp.batch[i,1], read.table(exp.batch[i,2]))

You don't want as.name: the argument of read.table is a character vector.

Reminder: get and assign are effectively the underlying functions for <-,
and they do work with character strings.  Use assign for the lhs and get
for the rhs.

I can recommend a good book on things like this: see the documentation
section on CRAN.   As ever with the S language there are other ways to do
it (but that's the Perl mantra).

Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list