Convert a column of strings in data frame into numeric in R (not the usual kind)

698 views Asked by At

So in R I have a column consisting of strings that look like something similar to this:

 "Peter","Paul","John","Melissa","Paul","Peter" ...

And I want to convert these names to a numerical ID format, like this:

  1,2,3,4,2,1

In other words - I want to create a numerical ID for the names where same names receive same numeric values, different names receive different numeric values. What are the best ways to do this?

1

There are 1 answers

0
akrun On BEST ANSWER

Try

 match(v1, unique(v1))
#[1] 1 2 3 4 2 1

Or

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

data

v1 <- c('Peter', 'Paul', 'John', 'Melissa', 'Paul', 'Peter')