In addition to @Ben's answer and those in the duplicate answer, you could use dplyr
to achieve this:
df %.% #your data.frame
group_by(ID) %.%
mutate(count = 1:n()) %.%
filter(count %in% max(c(count-1,1))) %.% #if each ID occures more than 1 time, you can simplify this to filter(count %in% max(count-1)) %.%
select(-count)
This can also be written in a single line:
df %.% group_by(ID) %.% mutate(count = 1:n()) %.% filter(count %in% max(c(count-1,1))) %.% select(-count)