Hi everyone, I have been working some days in a nested loop in R but I can't find the solution.
I have a data.frame with an unique ID for individuals and unique ID for different stands, for each indiviadual I have a dbh record and a SBA (stand basal area) field. Pma<-rep (1:40) P<-seq(1,4, 1) Plot<-rep(P,10) dbh2<-rnorm(40, mean=200, sd=5) SBA2<-rnorm(40, mean=10, sd=1) As I want to calculate the basal area of larger trees in each stand (i.e., the compare tree to tree the dbh and for each individual sum the stand basal area of larger trees) BAL2<-rep(0,length(Pma)) aa<-rep(0,length(Pma)) Now I have programed a for loop to do this calculation, and one plot it works quite well: kk<-data.frame(Pma, Plot, dbh2, SBA2, BAL2, aa) kkk<-kk[kk$Plot=="1",] The loop: for(j in 1:length(kkk$Pma)){ for(i in 1:length(kkk$Pma)){ if(kkk$dbh2[j]<kkk$dbh2[i]) kkk$aa[i]<-kkk$SBA2[i] else temp_data$aa[i]<-0 kkk$BAL2[j]<-sum(kkk$aa) } } But, I have tried a million of forms to calculate this for each stand... and no one looks fine. The closest code that I have got is: for(k in 1:length(kk)){ temp_data<-kk[kk$Plot==Plot[k],] for(j in 1:length(temp_data$Pma)){ #I have selected the individuals to calculate the BAL in each plot for(i in 1:length(temp_data$Pma)){ if(temp_data$dbh2[j]<temp_data$dbh2[i]) temp_data$aa[i]<-temp_data$SBA2[i] else temp_data$aa[i]<-0 temp_data$BAL2[j]<-sum(temp_data$aa) } ###Some suggestion to "save" the temporal data of each stand and group it together } } Any advise or suggestion will be very welcome, Thanks in advance, Paloma [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.