[R] help: program efficiency

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Thu Nov 25 16:48:24 CET 2010


one way is the following:

a <- c(2,1,1,3,3,3,4)

d <- unlist(sapply(rle(a)$length, function (x)
     if (x > 1) seq(0.01, by = 0.01, len = x) else 0))

a + d


I hope it helps.

Best,
Dimitris


On 11/25/2010 3:49 PM, randomcz wrote:
>
> hey guys,
>
> I am working on a function to make a duplicated value unique. For example,
> the original vector would be like : a = c(2,1,1,3,3,3,4)
> I'll like to transform it into:
> a.nodup = 2, 1.01, 1.02, 3.01, 3.02, 3.03, 4
> basically, find the duplicates and assign a unique value by adding a small
> amount and keep it in order.
> I come up with the following codes, but it runs slow if t is large. Is there
> a better way to do it?
> nodup = function(t)
> {
>    t.index=0
>    t.dup=duplicated(t)
>    for (i in 2:length(t))
>    {
>      if (t.dup[i]==T)
>        t.index=t.index+0.01
>      else t.index=0
>      t[i]=t[i]+t.index
>    }
>    return(t)
> }
>
>

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
Web: http://www.erasmusmc.nl/biostatistiek/



More information about the R-help mailing list