[R] Assign name to object for each iteration in a loop.

Patrick Connolly p_connolly at slingshot.co.nz
Sun Dec 4 05:16:25 CET 2011


On Thu, 01-Dec-2011 at 10:13AM -0800, lglew wrote:

|> Hi R-users,
|> 
|> I'm trying to produce decompositions of a multiple time-series, grouped by a
|> factor (called "area"). I'm modifying the code in the STLperArea function of
|> package ndvits, as this function only plots produces stl plots, it does not
|> return the underlying data. 
|> 
|> I want to extract the trend component of each decomposition
|> ("x$time.series[,trend]), assign a name based on the factor "area". 
|> 
|> My input data look like this:
|> Area is a factor, with three (but could be many more) levels.
|> area
|> 1
|> 2
|> 3
|> 
|> Ystart=2000
|> 
|> TS is a timeseries:
|> 
|>   X2000049   X2000065  X2000081  X2000097  X2000113 
|> 1     0.2080      0.2165      0.2149     0.2314      0.2028  
|> 2     0.1578      0.1671      0.1577     0.1593      0.1672   
|> 3     0.1897      0.1948      0.2290     0.2292      0.2067   
|> 
|> Here's the function:
|> 
|> STLpA<-function(TS, area, Ystart, period=23, nSG="5,5", DSG=0)
|> {
|> require (RTisean)
|> for(i in 1:unique(area)){
|> vi.metric=TS[area==i]
|> filt.vi<-sav_gol(vi.metric,n=nSG,D=DSG)
|> vi.sg<-ts(filt.vi[,1], start=Ystart,frequency=period)
|> stld.tmp<-stl(vi.sg, s.window="periodic", robust=TRUE, na.action=na.approx)
|> stld.trend<-stld.temp$time.series[,trend]
|> }
|> assign(paste("stld", i , sep= "."), stld.trend)
|> vi.trend<-ls(pattern= "^stld..$")
|> return(vi.trend)
|> }
|> 
|> When I call this function with signal=STLpA(TS,area,Ystart=2000,period=23,
|> nSG= "5,5", DSG="0"))
|> 
|> I get this error:
|> 
|> Error in cat(list(...), file, sep, fill, labels, append) : 
|>   argument 1 (type 'list') cannot be handled by 'cat'
|> In addition: Warning message:
|> In 1:unique(area) :
|>   numerical expression has 3 elements: only the first used
|> 
|> I'm guessing this is because I'm assigning names to each temporary stl.trend
|> file incorrectly. Can anyone 
|> improve on my rather poor efforts here?

I would suggest putting your individual trends into a list and
returning that at the end of your function rather than trying to
assing individual objects.  IMHO it's easier to do and more useful.
Something along these lines:


> trends <- list()
> for(i in 1:unique(area)){
...
+ trends[[i]] <- ....

}

Then you'll have an element in the list trends that you do with what
you will.  It creates less clutter also.

HTH



-- 
~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.   
   ___    Patrick Connolly   
 {~._.~}                   Great minds discuss ideas    
 _( Y )_  	         Average minds discuss events 
(:_~*~_:)                  Small minds discuss people  
 (_)-(_)  	                      ..... Eleanor Roosevelt
	  
~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.



More information about the R-help mailing list