Michael Rennie
2003-Jun-30 21:01 UTC
[R] Constructing loops in which i+1st element depends on ith
I feel greedy posting for help twice in one day- please forgive me, but the thesis can't wait. I have been trying to get an ?if else? statement working in a loop I am writing, in which I specify a variable value to 9.2 (Wo) on the first iteration, but for subsequent iterations, to adopt a value as a function of variables from the previous iteration. When I comment out the ?if else? statement, let W = Wo, and adjust the rest of the file so I am reading the first row of the variables specified instead of entire columns in my calculations, the calculations all work nicely without errors - I get the numbers I ought to in one row of ?bio?. When I activate the loop and try to run the file with ?the if .else?, it looks like it wants to work, but here?s where it stalls; Error in "[<-"(*tmp*, i, value = ((bio[i - 1, 1] * bio[i - 1, 9])/Ef)) : nothing to replace with Execution halted (see complete data file below)... I guess it?s because it can?t find the alternate case because it hasn?t written it yet. So, my problem is two-fold: 1. How can I write my loop properly so that at the end of each iteration, it records the row of data from ?bio? such that I can cbind it back to my ?Day? data? 2. How can I specify the loop to use information from the i+1st element in calculations for calculations in the ith? I?m pretty sure my problem is in where I create and specify files in the loop, but beyond that, I don?t know. Here?s the part of my command file that?s giving me trouble. Everything before this is simply specifying variable names to numbers, which is not giving be problems. #Bring in temp file temper <- scan("temp2.dat", na.strings = ".", list(Day=0, Temp=0)) #Day = day on which iteration begins, starts at day 1, ends on 366 #Temp = temperature Day <- temper$Day ; Temp<-temper$Temp ; temp<- cbind (Day, Temp) #temp [,2] p<- 0.558626306252032 ACT <- 1.66764519286918 Vc<-((CTM-temp[,2])/(CTM-CTO)) Vr<-((RTM-temp[,2])/(RTM-RTO)) comp<- cbind (Day, Temp, Vc, Vr) bio<-NULL M<- length(Day) #number of days iterated for (i in 1:M) { weight<- function(Day) { W<-NULL if (Day[i]==1) W[i] <- Wo {W[i] <- ((bio[i-1,1]*bio[i-1,9])/Ef) } W } W<-weight(Day) #W<-Wo C<- p*CA*(W^CB)*((comp[,3]^Xc)*(exp(Xc*(1-comp[,3]))))*Pc ASMR<- (ACT*RA*(W^(RB))*((comp[,4]^Xa)*(exp(Xa*(1-comp[,4]))))) SMR<- (ASMR/ACT) A<- (ASMR-SMR) F<- (FA*(comp[,2]^FB)*(exp(FG*p))*C) U<- (UA*(comp[,2]^UB)*(exp(UG*p))*(C-F)) SDA<- (S*(C-F)) Gr<- (C-(ASMR+F+U+SDA)) bio<- rbind(c(W, C, ASMR, SMR, A, F, U, SDA, Gr)) dimnames (bio) <-list(NULL, c ("W", "C", "ASMR", "SMR", "A", "F", "U", "SDA", "Gr")) } bio I would be grateful for any suggestions people might have. Thanks, Mike -- Michael Rennie M.Sc. Candidate University of Toronto at Mississauga 3359 Mississauga Rd. N. Mississauga ON L5L 1C6 Ph: 905-828-5452 Fax: 905-828-3792