[R] Again: Help with a loop (coefficients with lmList) (now with a good reproducible example)

Cecilia Carmo cecilia.carmo at ua.pt
Mon Aug 10 17:09:27 CEST 2009


Hi R-helpers:

#I start with the reproducible example:
firm<-sort(rep(1:1000,10),decreasing=F)
year<-rep(1998:2007,1000)
industry<-rep(c(rep(1,10),rep(2,10),rep(3,10),rep(4,10),rep(5,10),rep(6,10),rep(7,10),rep(8,10),rep(9,10),
rep(10,10)),1000)
X1<-rnorm(10000)
X2<-rnorm(10000,mean=0.5,sd=0.1)
Y<-rnorm(10000,mean=0,sd=0.5)
data<-data.frame(firm, industry,year,X1,X2,Y)
data

#I need to calculate for all the industries the following 
#coefficients and store it (lmList is from nlme package)
b1 <- lmList(Y~X1+X2| year, na.action=na.omit, data, 
subset=industry==1)
b2<-summary(b1)
b3<-as.data.frame(b2$coefficients)
b4<-round(b3,3)
b4

#Instead of changing the industry in the subset I want to 
do it at #once, so I’ve thinking in doing  a loop. Before 
I created an array to #store my coefficients:
years<-c("1998","1999","2000","2001","2002","2003","2004","2005","2006","2007")
industry<-sort(unique(data$industry))
coef<-c("Estimate.(Intercept)","Std. Error.(Intercept)","t
value.(Intercept)", "Pr(>|t|).(Intercept)", "Estimate.X1", 
"Std.
Error.X1","t value.X1", "Pr(>|t|).X1", "Estimate.X2", 
"Std. Error.X2", "t
value.X2", "Pr(>|t|).X2")
coefs<-array("NaN",dim=c(10,12,10),dimnames=list(years,coef,industry))
coefs

#The loop that I’ve tried was:
for (k in industry){
        b1 <- lmList(Y~X1+X2| year, na.action=na.omit, 
data, subset=industry==k)
	b2<-summary(b1)
	b3<-as.data.frame(b2$coefficients)
	b4<-round(b3,3)
	coefs[ , , k]<-b4[ , ]
}

#The error message is:
Error in coefs[, , k] <- b4[, ] : incorrect number of 
subscripts
Could anyone help me with this loop?

Thanks in advance,

Cecília (Universidade de Aveiro – Portugal)




More information about the R-help mailing list