[R] simple loop

Cecilia Carmo cecilia.carmo at ua.pt
Sun Jun 28 18:39:41 CEST 2009


Hi everyone!

I have this dataframe:

firm<-c(rep(1,4),rep(2,4),rep(3,4),rep(4,4),rep(5,4),rep(6,4))
year<-c(rep(2000:2003,6))
industry<-c(rep(10,4),rep(20,4),rep(30,4),rep(10,4),rep(20,4),rep(30,4))
X1<-c(10,14,18,16,20,45,23,54,24,67,98,58,16,32,57,12,54,0,0,22,11,3,5,6)
data<-data.frame(firm, industry,year,X1)
data

I need a loop that calculates the mean of X1 by year and 
by industry and I need this values in a dataframe or a 
matrix.
I have done:

means<-matrix(nrow=3,ncol=4)

for ( i in unique(data$industry))
  for (j in 
data$year){means[i,j]<-mean(data$X1,na.rm=TRUE)}

But it doesn´t work. Could anyone help me?

Cecília Carmo




More information about the R-help mailing list