Skip to content
Prev 140197 / 398506 Next

"spreading out" a numeric vector

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,