Home > Back-end >  Convert integers into their order of appearance
Convert integers into their order of appearance

Time:09-06

I would like to change a vector of integers into their order of appearance.

Suppose I have this vector:

c(3, 2, 3, 4, 4, 5, 5, 2, 1) 

The integer 3 appears first, so it should be 1.

The integer 2 appears second, so it should be 2. And so on.

The desired outcome:

1 2 1 3 3 4 4 2 6

CodePudding user response:

You can coerce to factor with unique values as levels.

as.numeric(factor(x, levels=unique(x)))
# [1] 1 2 1 3 3 4 4 2 5

Data:

x <- c(3, 2, 3, 4, 4, 5, 5, 2, 1) 

CodePudding user response:

You can use match function to find the order of appearance of unique values:

x <- c(3, 2, 3, 4, 4, 5, 5, 2, 1) 
match(x, unique(x))
[1] 1 2 1 3 3 4 4 2 5
  •  Tags:  
  • r
  • Related