[R] Re move repeated values

Erik Iverson iverson at biostat.wisc.edu
Wed Oct 8 22:12:59 CEST 2008



kathie wrote:
> Dear R users,
> 
> I'd like to make this data
> 
> 	rem.y = c(-1,0,2,4,5)
> 
> from 
> 
> 	y = c(-1,-1,0,2,2,2,2,4,4,5,5,5,5,5).
> 
> That is, I need to remove repeated values.
> 
> 
> Here is my code, but I don't think it is efficient.  How could I improve
> this?
> 
> 

By using the 'unique' function, as in,

rem.y <- unique(y).

Almost any time you use subscripts, you should ask yourself if there's a 
vectorized function already available.


> #------------------------------------------------------------------------
> y = c(-1,-1,0,2,2,2,2,4,4,5,5,5,5,5)
> n=length(y)
> 
> for (i in 1:n)          # removed same values in y
> {
> 	imsi = 0
> 	if (i==1) {rem.y = y[i]}
> 	else {c = length(rem.y)
> 	      for (j in 1:c) { if (y[i]==rem.y[j]) imsi=1 }
> 	      if (imsi==0) rem.y = c(rem.y,y[i])}
> }
> 
> rem.y
> #-------------------------------------------------------------------------
> 
> 
> Any suggestion will be greatly appreciated.
> 
> Regards,
> 
> Kathryn Lord



More information about the R-help mailing list