How to find position (index) of elements based on

2019-02-25 15:00发布

问题:

Let's say I have a vector V of categorical variable L = c("a", "b", "c"):

V <- c("a", "a", "b", "c", "b", "c")

I want to encode every value of L with numbers and update V according to this encoding.

So, the new vector is:

Vnew = c(1, 1, 2, 3, 2, 3)

Would you help me with it?

回答1:

I would consider using factor and extract the underlying numeric representation. Usage would simply be:

as.numeric(factor(V, L))
# [1] 1 1 2 3 2 3


回答2:

You can just use match

match(V,L)
#[1] 1 1 2 3 2 3