[R] assign() won't work

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Sun May 25 11:36:43 CEST 2003


"Brian J. Lopes" <blopes at email.unc.edu> writes:

> Hey everyone, I've been searching the mail lists, and I can't find a
> real discussion about my problem. Here it is:
> 
> I have created a loop fitting various time series models to my data.
> I labeled each one of the outputs by using the assign and paste
> statements, i.e. assign(paste("group","subgroup",i),arima(...)).
> Works great, but here's what I need...
> 
> I want to create a tables by group, and refer to particular
> information from each arima fit, such as AIC value, loglikelihood
> value, etc.
> 
> My best guess is,
> assign(paste("group","subgroup"),get(paste("group",subgroup",i))$aic
> 
> This won't work, due to the restrictions of my the assign function.
> If you can't understand this from the code, here it is verbally:
> 
> I've got a bunch of matrices to fill-in with information, all their
> names are part of this paste function (59 in total). I want to fill
> in the rows of each matrix with the information from every analysis
> provided for each group. (i.e. for ARMA(1,0) I want a row of the aic
> and loglikelihood values, but I want this for the ARMA(1,1) model I
> ran, and the ARMA(2,0) model I ran as well) I have done many ARMA's
> for many different series, and want to make a table for each series.
> There are too many of these to do this for each individual series.

(please wrap your lines...)

Every time someone asks the question "How do I assign to x1,x2,x3,..."
they get the answer that assign(paste("x",i,sep=""),...) will work,
but they'd probably be better off using lists. I suspect you're in the
process of finding out why: The R language works much better on data
structures than on string representations. 

I'm not going to try and sort out the full details of your problem,
but if you had a list of arima() results, the solution could be as
simple as

sapply(olist,function(o)unlist(o[c("loglik","aic")]))

Here's a simple example, continuing example(arima):

data(lh)
l <- list(c(1,0,0),c(3,0,0),c(1,0,0))
olist <- lapply(l,arima, x=lh)
names(olist) <- sapply(l,deparse) 
sapply(olist,function(o)unlist(o[c("loglik","aic")]))

There are a couple of variations: (a) You might want to transpose the
resulting matrix using t(..) and (b) there's a simpler form

sapply(olist,"[",c("loglik","aic"))

but notice that (since the unlist() is gone) that gives you a list
matrix, rather than a matrix of numbers so the formatting is
different. (Run str() on the output to see what I mean.)

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list