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

Jarimatti Valkonen javalkon at hytti.uku.fi
Wed Aug 16 10:05:03 CEST 2006


On Wed, Aug 16, 2006 at 10:42:35AM +0300, Atte Tenkanen wrote:
> 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

How about rle? rle(VECTOR)$values should do the same thing. Don't know
about efficiency, though.

-- 
Jarimatti Valkonen



More information about the R-help mailing list