Ian
Ian

Reputation: 173

Convert integers into their order of appearance

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

Upvotes: 1

Views: 50

Answers (2)

Karol Daniluk
Karol Daniluk

Reputation: 544

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

Upvotes: 2

jay.sf
jay.sf

Reputation: 73562

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) 

Upvotes: 2

Related Questions