[R] "spreading out" a numeric vector

Levi Waldron leviwaldron at gmail.com
Sun Mar 23 02:03:02 CET 2008


I am creating a timeline plot, but running into a problem in positions
where the values to plot are too close together to print the text
without overlap.  The simplest way I can think of to solve this
(although there may be other ways?) is to create a new numeric vector
whose values are as close as possible to the original vector, but
spread out to a given minimum difference.  For example, take the
following vector:

> x <- c(1,2,seq(2.1,2.3,0.1),3,4)
> x
[1] 1.0 2.0 2.1 2.2 2.3 3.0 4.0
>

However, suppose I don't want to plot any of these points with less
than 0.5 between them.  The problem could be solved by a function that
behaved something like this:

> x2 <- spread(x,mindiff=0.5)
> x2
[1] 0.5 1.0 1.5 2.0 2.5 3.0 4.0

Or for a minimum difference of 0.2,
> x2 <- spread(x,mindiff=0.2)
> x2
[1] 1.0 1.8 2.0 2.2 2.4 3.0 4.0

Thus, if there is a cluster of close values, spreading the values may
require changing values which previously weren't too close to their
nearest neighbors.

Then I could use segments() to draw lines from the timeline to where
the shifted text is printed, labeling tics on the timeline accurately
but keeping the text from overlapping.

Any ideas on how to program this or how to do it using built-in
functions would be greatly appreciated.



More information about the R-help mailing list