[R] function returns R object with name based on input

Jennifer Brea brea at fas.harvard.edu
Fri Apr 24 17:56:33 CEST 2009


I wanted to ask how I can make a for loop or a function return an R 
object with a unique name based on either some XX of the for loop or 
some input for the function.

For example

if I have a function:

fn<-function(data,year){

which does does some stuff
}

How do I return an object from the function called X.year, such that if 
I run fn(data,1989), the output is an object called X.1989?

In a separate but related process, I'm also trying to subset data by 
year, where there are multiple observations by years, using the subset() 
function.  For example:

data.1946<-subset(data, year==1946)
data.1947<-subset(data, year==1947)
data.1948<-subset(data, year==1948)
data.1949<-subset(data, year==1949)
...

How should I set this up?  I was thinking of writing a for loop, but I 
have never written a for loop that creates objects based on the loop's 
index, for example a loop for(i in 1946:2000) that returns 55 objects 
with the object names based on the index.

Thanks for your help!




More information about the R-help mailing list