Dear R-Users, I have the following problem of which I have provided a simple example. Using the tapply command I can efficiently run the function genflo for all months and years. I am new to R and I do not understand how I can store the results of f such that as the function loops through the months, I can retrieve the tail value of f from the previous month and use this as a condition for the current month iteration (note the comments in the code). Forgive me if I am not clear.
Thanks in advance Floris year <- c(1972, 1972, 1972, 1972, 1972, 1972, 1972, 1972, 1972, 1972, 1972, 1972) month <- c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3) discharge <- c(100921, 89885, 81493, 74876, 70579, 68305, 66337, 63095, 58446, 52674, 44028, 31956) n11 <- c(1,1,1,1,1,1,1,1,1,1,1,1) n00 <- c(0,0,0,0,0,0,0,0,0,0,0,0) n01 <- c(0,0,0,0,0,0,0,0,0,0,0,0) n10 <- c(0,0,0,0,0,0,0,0,0,0,0,0) flow_data <- data.frame(year, month, discharge, n11, n00, n01, n10) genflo <- function(X) { n <- nrow(X) if((sum(X$n11) + sum(X$n10)) > 0) { Pww <- sum(X$n11)/(sum(X$n11) + sum(X$n10)) } else {Pww <- 0} if((sum(X$n00) + sum(X$n01)) > 0) { Pdd <- sum(X$n00)/(sum(X$n00) + sum(X$n01)) } else {Pdd <- 0} r <- vector(length = n) rand <- runif(r, 0, 1) f <- vector(length = n) # for (i in 2:n) { # if(X$discharge[i-1] > 0) { # X$discharge needs to be replaced by # the tail value of f from the # previous iteration (month) if(rand[i] > Pww) { f[i] <- 0 } else {f[i] <- 1} } else {if(rand[i] > Pdd){ f[i] <- 1 } else {f[i] <- 0} } } return(f) } gen_flow_days <- by(flow_data, list(month = flow_data[,2], year = flow_data[,1]), genflo) gen_flow_days <- unlist(gen_flow_days) ______________________________________________ R-help@stat.math.ethz.ch 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.