将数字转换为字母 [英] Convert numbers to letters

查看:100
本文介绍了将数字转换为字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下向量:

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

我该如何做?我敢打赌,这里有一个简单的答案,它会通过使用保留的LETTERS向量来完成,但我找不到解决方案.这是迄今为止我能设法解决的最好的问题(您可能希望将孩子带出房间):

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"

推荐答案

由于这仅涉及一对一的字符替换,因此仅使用chartr()

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"

这篇关于将数字转换为字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆