[R] the first and last case

Jacques VESLOT jacques.veslot at good.ibl.fr
Wed Jul 26 15:09:37 CEST 2006


do.call(rbind,lapply(split(dat, dat$ind), function(x) x[c(1,nrow(x)),]))
-------------------------------------------------------------------
Jacques VESLOT

CNRS UMR 8090
I.B.L (2ème étage)
1 rue du Professeur Calmette
B.P. 245
59019 Lille Cedex

Tel : 33 (0)3.20.87.10.44
Fax : 33 (0)3.20.87.10.31

http://www-good.ibl.fr
-------------------------------------------------------------------


Mauricio Cardeal a écrit :
> Hi all
> 
> Sometime ago I asked for a solution about how to aggregate data and the 
> help was wonderful. Now, I´d like to know how to extract for each 
> individual case below the first and the last observation to obtain this:
> 
> ind  y
> 1    8
> 1    9
> 2    7
> 2   11
> 3    9
> 3   10
> 4   8
> 4   5
> 
> # Below the example:
> 
> ind <- c(1,1,1,2,2,3,3,3,4,4,4,4)
> y <- c(8,10,9,7,11,9,9,10,8,7,6,5)
> dat <- as.data.frame(cbind(ind,y))
> dat
> attach(dat)
> mean.ind <- aggregate(dat$y, by=list(dat$ind), mean)
> mean.ind
> 
> Thanks
> Mauricio
> 
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>



More information about the R-help mailing list