Jennifer Brea
2009-Apr-24 15:56 UTC
[R] function returns R object with name based on input
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!
David Winsemius
2009-Apr-24 16:54 UTC
[R] function returns R object with name based on input
On Apr 24, 2009, at 11:56 AM, Jennifer Brea wrote:> 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?Read: ?assign ?paste #and FAQ 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f> > 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) > ...list.of.subsets <- sapply(1946:200, function(x) subset(data, year==x) ) # with no example ... untested Using data as a dataframe names is poor R programming practice, since many functions use data a a parameter name and it is also a function name.> > > 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. >David Winsemius, MD Heritage Laboratories West Hartford, CT