The solution in the R database using split-apply-combination works through the tail function, which returns the last element and rle in combination with mapply to create a new events vector that preserves order in case of repeated events:
x <- read.table(text = " events time a t1 b t2 b t3 b t4 c t5 c t6 b t7 d t8", header = TRUE) # create vector of new.events (ie, preserve reappearing objects) occurences <- rle(as.character(x$events))[["lengths"]] new.events <- unlist(mapply(rep, x = letters[seq_along(occurences)], times = occurences)) # split into sublists per event s1 <- split(x, list(new.events)) # get last element from list s2 <- lapply(s1, tail, n = 1) # combine again do.call(rbind, s2)
This gives the desired result.
source share