I have a bunch of letters, and cannot for the life of me figure out how to convert them to their number equivalent.
letters[1:4]
Is there a function
numbers['e']
which returns
5
or something user defined (ie 1994)?
I want to convert all 26 letters to a specific value.
The Letter-to-Number Cipher (or Number-to-Letter Cipher or numbered alphabet) consists in replacing each letter by its position in the alphabet , for example A=1, B=2, Z=26, hence its over name A1Z26 .
Select all the cells that you want to convert from text to numbers. Click on the yellow diamond shape icon that appears at the top right. From the menu that appears, select 'Convert to Number' option.
In the cell, type 1, and then press ENTER. Select the cell, and then press Ctrl+C to copy the value to the Clipboard. Select the cells or ranges of cells that contain the numbers stored as text that you want to convert. Click the cell, or press the arrow keys to move to the cell.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With