I've also tried to make the function work for one particular group, then apply the same function to the whole data frame with all groups using by() or lapply() as follow. But I'm still receiving error messages. Could someone please explain what is happening here?
dfdfdf <- function(localdata){ ordering <- c() ordering[1] <- ifelse(localdata[1, ]$prev_event == 0, localdata$event, localdata[1, ]$prev_event) for (i in 2:nrow(localdata)){ ordering[i] <- localdata[localdata$prev_event == ordering[i-1], ]$event} } by(mydata, INDICES = mydata$group, FUN = dfdfdf) lapply(mydata, FUN = dfdfdf) Error in ordering[i] <- localdata[localdata$prev_event == ordering[i - : replacement has length zero In addition: Warning message: In ordering[i] <- localdata[localdata$prev_event == ordering[i - : number of items to replace is not a multiple of replacement length Thanks a lot!! -- View this message in context: http://r.789695.n4.nabble.com/R-loop-within-a-loop-tp3898001p3898300.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ 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.