[R] "spreading out" a numeric vector

Levi Waldron leviwaldron at gmail.com
Mon Mar 24 21:14:12 CET 2008


*Thank you* Greg, this function works perfectly!  I had imagined that
the ideal solution would iteratively modify the vector to fix new
violations of mindiff created by each subsequent spreading of tight
clusters, but couldn't figure how to do it.  A small note, the vector
x must be sorted before using this function, which is a reasonable
requirement.

Thanks also to Jim Lemon for pointing out the very useful plotrix
package - the spread.labels function didn't work so well for this
application because the timelines looked strange with the labels
spread evenly, but I like a number of the functions provided by the
package.

-levi

On Mon, Mar 24, 2008 at 12:43 PM, Greg Snow <Greg.Snow at imail.org> wrote:
> Levi,
>
>  Here is one possible function:
>
>  spread <- function(x, mindiff) {
>   df <- x[-1] - x[-length(x)]
>   i <- 1
>   while (any(df < mindiff)) {
>     x[c(df < mindiff, FALSE)] <- x[c(df < mindiff, FALSE)] - mindiff/10
>     x[c(FALSE, df < mindiff)] <- x[c(FALSE, df < mindiff)] + mindiff/10
>     df <- x[-1] - x[-length(x)]
>     i <- i + 1
>     if (i > 100) {
>        break
>     }
>   }
>   x
>  }
>
>  I have tried experimenting with using optim to minimize a function of
>  the distances between new points and old points penealized for being to
>  close, but it sometimes gave me some weird results, the above has worked
>  fairly well for me (the above is based on some of the code inside the
>  triplot function in the TeachingDemos package).
>
>  Hope this helps,
>
>  --
>  Gregory (Greg) L. Snow Ph.D.
>  Statistical Data Center
>  Intermountain Healthcare
>  greg.snow at imail.org
>  (801) 408-8111



More information about the R-help mailing list