[R] problem with nested loops

David Winsemius dwinsemius at comcast.net
Tue Feb 26 23:28:27 CET 2013


On Feb 26, 2013, at 1:53 PM, Richard Saba wrote:

> Each of the data sets contains monthly observations on price indices for 7 countries. I use the fitted values from reg1 in the reg2 model. The interior loop executes without error as long as I explicitly specify the data set, i.e. data=dat70. However the code fails to execute if I specify the model in the form of the commented line, i. e   reg1 <-dynlm(form1,data=Dnames[j])
> I get the following error message:
> 
> 
> Error in merge.zoo(USA, lag(USA, k = -1), lag(USA, k = -2), lag(Canada,  :
> 
>  object 'USA' not found


> 
> 
> Apparently the Dnames[j] does not evaluate to the dataset name. Does anyone have a solution to my problem?
> 
> The values in Names are:
> 
>  [1] "Canada"  "France"  "Germany" "Italy"   "Japan"   "UK"      "USA"
> 
> 
> 
> And in Dnames are :
> 
> [1] "dat70"   "dat80"   "dat90"   "dat2000"
> 
> 
> library(dynlm)
> kimdat<-ts(read.csv("data.csv", header = TRUE),start=1970,frequency=12)
> dat70 <- window(kimdat,start =c(1970,1), end=c(1979,12))
> dat80 <- window(kimdat,start =c(1980,1), end=c(1989,12))
> dat90 <- window(kimdat,start =c(1990,1), end=c(1999,12))
> dat2000 <- window(kimdat,start =c(2000,1), end=c(2009,12))
> Names<-colnames(kimdat)
> 
> Dnames <- c("dat70","dat80","dat90","dat2000")

Convert to a list:

Dnames <- c(dat70, dat80, dat90, dat2000)

> for (j in 1:4) {
>         for( i in 7:2) {
>       form1<-as.formula(paste(Names[i],"~","lag(",Names[i],",k=-1) + lag(",Names[i],",k=-2)+ lag(",Names[1],",k=-1) +lag(",Names[1],",k=-2)"))
>       form2<-as.formula(paste(Names[1],"~fitted(reg1)"))
> 
# And then use "[[" to get the values rather than a sublist:

        reg1 <-dynlm(form1,data=Dnames[[j]])
     reg2 <-dynlm(form2,data=Dnames[[j]])

>     # reg1 <-dynlm(form1,data=dat80)
>    #  reg2 <-dynlm(form2,data=dat80)
>     print(summary(reg1))
>      print(summary(reg2))
>  }
> }
> 
> Thanks,
> Richard Saba
> 
> 	[[alternative HTML version deleted]]

And please learn to post in plain text and please do read the rest of the Posting Guide that I did not just repeat for you.

-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list