[R] For-loop
Anne-Christine Mupepele
anne-chr.afs at web.de
Mon Dec 20 11:48:51 CET 2010
Hi,
I have the following problem:
I have a data.frame with 36 sample sites (colums) for which I have covariates in 3 categories: Area, Month and River. Each Area consists of 3 rivers, which were sampled over 3 month. Now I want to fuse River 1-3 for one area in one month. To get a data.frame with 12 colums.
I am trying to do a "for loop" (which may be a complicated solution, but I don't see an easier way), which is not working, apparently because a[,ij] or a[,c(i,j)] is not working as a definition of the matrix with a double condition in the colums.
How can I make it work or what would be an easier solution?
Thank you for your help,
Anne
data=data.frame(matrix(1:99,nrow=5,ncol=36))
colnames(data)=c(paste("plot",1:36))
cov=data.frame(rep(1:3,12),c(rep("Jan",12),rep("Feb",12),rep("Mar",12)),rep(c(1,1,1,2,2,2,3,3,3,4,4,4),3))
dimnames(cov)=list(colnames(data),c("River","Month","Area"))
###loop###
a=matrix(nrow=dim(data)[1],ncol=length(levels(factor(cov$Month)))*length(levels(factor(cov$Area))))
for(i in 1:length(levels(factor(cov$Month))))
{
for(j in 1:length(levels(factor(cov$Area))))
{
a[,ij]=as.numeric(rowSums(data[,factor(cov$Month)==levels(factor(cov$Month))[i]&factor(cov$Area)==levels(factor(cov$Area))[j]]))
}
}
More information about the R-help
mailing list