Skip to content
Prev 70342 / 398506 Next

obtaining first and last record for rows with same identifier

If you want to obtain a data frame you can use the functions head and tail 
like:

dat=data.frame(id=rep(1:5,3),num=rnorm(15), num2=rnorm(15))#Creates data 
frame with id
last=do.call("rbind",by(dat,dat$id,tail,1))#Selects the last observation for 
each id
first=do.call("rbind",by(dat,dat$id,head,1))#Selects the first observation 
for each id
newdat=rbind(first,last)#Joins data
newdat=newdat[order(newdat$id),]#sorts data by id

Notice that rownames will give you the original row location of the 
observations selected

I hope this helps

Francisco