convert letters to numbers

六月ゝ 毕业季﹏ 提交于 2019-11-27 02:05:29

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:

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

Here's a short test:

letter2num("e")
#[1] 5
set.seed(123)
myletters <- letters[sample(26,8)]]
#[1] "h" "t" "j" "u" "w" "a" "k" "q"
unname(sapply(myletters, letter2num))
#[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}

Create a lookup vector and use simple subsetting:

x <- letters[1:4]
lookup <- setNames(seq_along(letters), letters)
lookup[x]
#a b c d 
#1 2 3 4 

Use unname if you want to remove the names.

MrAesthetic

The which function seems appropriate here.

which(letters == 'e')
#[1] 5

thanks for all the ideas, but I am a dumdum.

Here's what I did. Made a mapping from each letter to a specific number, then called each letter

df=data.frame(L=letters[1:26],N=rnorm(26))
df[df$L=='e',2]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!