[R] How to use macro variable in a text string

Steve Lianoglou mailinglist.honeypot at gmail.com
Thu Jul 23 00:29:00 CEST 2009


Hi,

On Jul 22, 2009, at 5:46 PM, kxk wrote:

> I want to use read.table to input many files, each for a different  
> year.  I
> would like to use the macro variable 't' to refer to the exact file  
> that I
> would like to input the data using read.table.  How could I do  
> this?  Thank
> you!
>
> for (t in 1970:2005)
> { edge <- read.table(file="edge_t.csv", header=T,  sep=",")
> ## I will  have many rows of code following the read.table line
> }

Two things:

1. Not extremely important here at all, but for the future: just note  
that but by using "t" you're trampling over the transpose function  
t(), so perhaps you can use a more descriptive variable to both make  
code more readable and less ... urm, trample-itve :-)

2. Answer:

for (year in 1970:2005) {
   edge <- read.table(file=sprintf("edge_%d.csv", year), header=T,  
sep=",")
   ...
}

You can also use the paste function in place of sprintf

-steve

--
Steve Lianoglou
Graduate Student: Physiology, Biophysics and Systems Biology
Weill Medical College of Cornell University

Contact Info: http://cbio.mskcc.org/~lianos/contact




More information about the R-help mailing list