Solved – How to convert a vector of enumerable strings into a vector of numbers?

r

How to convert the x below to into a vector like y?

x <- ["a", "b", "b", "c", ...]

y <- [1, 2, 2, 3, ...]

UPDATE:

I end up with:

levels(x) <- 1:length(levels(x))

Best Answer

Here is a possibility, very similar than that of @Roman Lustrik, but just a little bit more automatic.

Say that

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

Then

   > x <- as.factor(x)
   > levels(x) <- 1:length(levels(x))
   > x <- as.numeric(x)

makes the job:

   > print(x)
   [1] 1 2 2 3