Make all elements of a vector different

Viewed 63

I have a vector (specifically with 770 elements) and some of them are repeated. I want all of them to be different. I have developed a code (a simple loop) to sum 0.0000001 when two positions hold the same number so as to make the value slightly different. However, the code doesn't work and I don't know how to correct it. It fails when more than 2 consecutive positions hold the same value.

I am sure it is going to be a fairly simple solution but I can't seem to find it. The code in in R.

for (i in 1:769) {
  if (grid.x[i] == grid.x[i+1]) {
    grid.x[i+1] <- grid.x[i+1] + 0.0000001
  }
}
3 Answers

Try this:

vec <- c(1,2,3,4,3,3,4)
ave(vec, vec, FUN=function(z) z+(seq_along(z)-1)*1e-4)
# [1] 1.0000 2.0000 3.0000 4.0000 3.0001 3.0002 4.0001

Notice that the 3s have incremental additions. I used 1e-4, feel free to go with something smaller.

We can use make.unique

as.numeric(make.unique(as.character(vec)))
#[1] 1.0 2.0 3.0 4.0 3.1 3.2 4.1

data

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

Another ave version

> vec + 1e-4 * (ave(vec, vec, FUN = seq_along) - 1)
[1] 1.0000 2.0000 3.0000 4.0000 3.0001 3.0002 4.0001
Related