Convert letters to numbers

I don’t know of a “pre-built” function, but such a mapping is pretty easy to set up using match. For the specific example you give, matching a letter to its position in the alphabet, we can use the following code:

myLetters <- letters[1:26]

match("a", myLetters)
[1] 1

It is almost as easy to associate other values to the letters. The following is an example using a random selection of integers.

# assign values for each letter, here a sample from 1 to 2000
set.seed(1234)
myValues <- sample(1:2000, size=26)
names(myValues) <- myLetters

myValues[match("a", names(myValues))]
a 
228

Note also that this method can be extended to ordered collections of letters (strings) as well.

Leave a Comment