Home > Enterprise >  How to create a vector of positions of a numeric vector in R?
How to create a vector of positions of a numeric vector in R?

Time:12-03

I have a vector of numbers that contain some gaps. For example,

vec <- c(3,1,7,3,5,7)

So, there are 4 different values and I would like to transform it into a vector of values (without gaps) indicating the order of the entry while respecting the same position. So, in this case, I would like to obtain

2 1 4 2 3 4 

Indicating a sequence of between 1 and 4 and showing the orders in the original vector vec.

CodePudding user response:

You can use match to help you look up the values in a sorted unique order. For example

vec <- c(3,1,7,3,5,7)
match(vec, sort(unique(vec)))
# [1] 2 1 4 2 3 4

This works because match returns the indexes which will start at 1.

CodePudding user response:

We may use factor

as.integer(factor(vec))
[1] 2 1 4 2 3 4
  • Related