1

I have a vector of integers, for example, v <- c(1,5,1,2,2,4,7,5,7). If I sort(unique(v)), the values 3 and 6 would be missing in the sequence. How can I transform v into a vector where sort(unique(v)) is an actual sequence of integers? This is, transforming v into c(1,4,1,2,2,3,5,3,5) (in general, of course).

Trilobite
  • 37
  • 4

2 Answers2

2

Converting v to factor and back to numeric could do the trick

as.numeric(as.factor(v))
#[1] 1 4 1 2 2 3 5 4 5
d.b
  • 32,245
  • 6
  • 36
  • 77
2

Using OP's method, we get the expected output with match

match(v, sort(unique(v)))
#[1] 1 4 1 2 2 3 5 4 5
akrun
  • 874,273
  • 37
  • 540
  • 662