Skip to content

How to remove similar successive objects from a vector?

5 messages · Atte Tenkanen, Dimitris Rizopoulos, Jacques VESLOT +2 more

#
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])}
}
[1] 3 2 4 5 5 3 3 5 1 6 6
[1] 3 2 4 5 3 5 1 6

_______________________________
Atte Tenkanen
University of Turku, Finland
#
try something like the following:

x <- c(3,3,2,4,5,5,3,3,5,1,6,6)
#########
nx <- length(x)
ind <- c(TRUE, (x[1:(nx-1)] - x[2:nx]) != 0)
x[ind]


I hope it helps.

Best,
Dimitris

----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://med.kuleuven.be/biostat/
     http://www.student.kuleuven.be/~m0390867/dimitris.htm


----- Original Message ----- 
From: "Atte Tenkanen" <attenka at utu.fi>
To: <r-help at stat.math.ethz.ch>
Sent: Wednesday, August 16, 2006 9:42 AM
Subject: [R] How to remove similar successive objects from a vector?
Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm
#
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 :
#
On Wed, Aug 16, 2006 at 10:42:35AM +0300, Atte Tenkanen wrote:
How about rle? rle(VECTOR)$values should do the same thing. Don't know
about efficiency, though.
#
On Wed, 2006-08-16 at 10:42 +0300, Atte Tenkanen wrote:
Is this what you mean?

x <- c(3, 2, 4, 5, 5, 3, 3, 5, 1, 6, 6)
x.wanted <- c(3, 2, 4, 5, 3, 5, 1, 6)

X <- x[diff(x) != 0]

all.equal(x.wanted, X) # check it works

G