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.


You could try this function:

letter2number <- function(x) {utf8ToInt(x) - utf8ToInt("a") + 1L}

Here's a short test:

letter2number("e")
#[1] 5
set.seed(123)
myletters <- letters[sample(26,8)]
#[1] "h" "t" "j" "u" "w" "a" "k" "q"
unname(sapply(myletters, letter2number))
#[1]  8 20 10 21 23  1 11 17

The function calculates the utf8 code of the letter that it is passed to, subtracts from this value the utf8 code of the letter "a" and adds to this value the number one to ensure that R's indexing convention is observed, according to which the numbering of the letters starts at 1, and not at 0.

The code works because the numeric sequence of the utf8 codes representing letters respects the alphabetic order.


For capital letters you could use, accordingly,

LETTER2num <- function(x) {utf8ToInt(x) - utf8ToInt("A") + 1L}

Tags:

R