[R] How to remove similar successive objects from a vector?

Jacques VESLOT jacques.veslot at good.ibl.fr
Wed Aug 16 10:01:04 CEST 2006


VECTOR=c(3,2,2,3,4,4,5,5,5,3,3,3,5,1,6,6)
NEWVECTOR <- ifelse(VECTOR[-length(VECTOR)]==VECTOR[-1],NA,VECTOR)
NEWVECTOR[!is.na(NEWVECTOR)]
[1] 3 2 3 4 5 3 5 1

-------------------------------------------------------------------
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
-------------------------------------------------------------------

Atte Tenkanen a écrit :
> Is there some (much) more efficient way to do this?
> 
> VECTOR=c(3,2,4,5,5,3,3,5,1,6,6);
> NEWVECTOR=VECTOR[1];
> 
> for(i in 1:(length(VECTOR)-1))
> {
> 	if((identical(VECTOR[i], VECTOR[i+1]))==FALSE){
> 		NEWVECTOR=c(NEWVECTOR,VECTOR[i+1])}
> }
> 
> 
>>VECTOR
> 
>  [1] 3 2 4 5 5 3 3 5 1 6 6
> 
>>NEWVECTOR
> 
> [1] 3 2 4 5 3 5 1 6
> 
> _______________________________
> Atte Tenkanen
> University of Turku, Finland
> 
> ______________________________________________
> 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