Convert labels to numeric labels

3

I have labels stored as letters and want to convert to numeric, for example:

a <- c("A", "B", "A", "A", "C", "E", "D", "A", "B")

Desired output

[1] 1 2 1 1 3 5 4 1 2
    
asked by anonymous 14.11.2016 / 16:14

1 answer

4

Transform your vector a into factor and then convert it to numeric:

as.numeric(factor(a))
[1] 1 2 1 1 3 5 4 1 2

You can even assign different numeric values for a levels. For example,

as.numeric(factor(a, levels=c("E", "D", "C", "B", "A")))
[1] 5 4 5 5 3 1 2 5 4
    
14.11.2016 / 17:32