[R] Looping through R objects

Steve Lianoglou mailinglist.honeypot at gmail.com
Wed Jul 29 02:27:46 CEST 2009


On Jul 28, 2009, at 5:39 PM, Vivek Ayer wrote:

> That just creates one object and doesn't contain any $ subobjects in
> it. Here's what I did to figure it out (It's complicated):
>
> for(i in c(1:13))
> assign
> (paste
> ("bc",i,sep=""),read.csv(paste(i,".csv",sep=""),sep="",header=TRUE))
>
> in shorthand: for {assign(paste,read(paste))}
>
> This creates individual objects for each csv file and allows me to
> have $ subjects, e.g., bc1$foo.

Well, as Rolf mentioned, while this works, this isn't "the cleanest."  
Not that it matters if you're just trying to get something done  
quickly and move on, but let me just show you perhaps a more idiomatic- 
R way to do this .. continuing from my last example:

objects <- lapply(1:13, function(i) {
  read.csv(paste(i, 'csv', sep='.'), header=TRUE, sep="")
})
names(objects) <- paste('bc', 1:13, sep='')

## Now your list indices are named just like the way you want them
## You'd generally access each table like:
## objects$bc1, objects$bc2, etc.
## You seem to want them in your 'global' soup, and the attach
## function can do this for you
attach(objects)

## .. now you can access the objects from within the list w/o
## referencing the list, eg: bc1, bc2 etc.
## .. once you're done using these object, clean up your
## environment:
detach(objects)

You can also look at ?with for another way to do the same w/o the  
attach/detach calls.

Just wanted to show you another way to get at what you wanted ... take  
it or leave it, your choice :-)

-steve

--
Steve Lianoglou
Graduate Student: Computational Systems Biology
   |  Memorial Sloan-Kettering Cancer Center
   |  Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact




More information about the R-help mailing list