[R] Optimize for loop / find last record for each person

Andrew Ziem ahz001 at gmail.com
Fri Feb 27 20:02:31 CET 2009

I want to find the last record for each person_id in a data frame
(from a SQL database) ordered by date.  Is there a better way than
this for loop?

for (i in 2:length(history[,1])) {
    if (history[i, "person_id"] == history[i - 1, "person_id"])
      history[i, "order"] = history[i - 1, "order"] + 1 # same person
      history[i, "order"] = 1 # new person

# ignore all records except the last for each con_id
history2 <- subset(history, order == 1)


More information about the R-help mailing list