Convert numbers to letters

牧云@^-^@ 提交于 2019-12-18 07:52:37

问题


I have the following vector:

x <- c(11, 12, 21, 22)

And I want to convert it to the corresponding letters, i.e., I want to get this result:

AA AB BA BB

How do I make this? I bet there's a simple answer and that it goes through using the reserved LETTERS vector, but I can't figure out a solution. This is the best I've managed to come up with so far (you might want to take the kids out of the room):

> paste0(gsub(1, LETTERS[1], substr(x, 1, 1)),
         gsub(2, LETTERS[2], substr(x, 1, 1)))
[1] "A1" "A1" "2B" "2B"

回答1:


Since this just involves one-to-one character substitution, it might be simplest to just use chartr()

chartr("123456789", "ABCDEFGHI", x)
# [1] "AA" "AB" "BA" "BB"



回答2:


Without libraries, the compact one-line solution is

sapply(strsplit(paste(x),''), function(y) paste(LETTERS[as.numeric(y)], collapse = ''))
# [1] "AA" "AB" "BA" "BB"



回答3:


Like this?

x <- c(11, 12, 21, 22)

s1 = as.numeric(substr(x, start=1, stop=1))
s2 = as.numeric(substr(x, start=2, stop=2))

print(paste0(LETTERS[s1], LETTERS[s2]))

>[1] "AA" "AB" "BA" "BB"



回答4:


or like this:

sapply(strsplit(as.character(c(123,11,22,5612)),""), function(x) paste0(LETTERS[as.integer(x)], collapse=""))
    ## [1] "ABC"  "AA"   "BB"   "EFAB"


来源:https://stackoverflow.com/questions/23117096/convert-numbers-to-letters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!