我已经从stringr包中检查了很多R函数,但是找不到正确的答案。我正在尝试将例如2211578的数字转换为字符串,其中每个字母均由我的全局数字中每个位置的整数给出。例如,如果我的电话号码是2211578,我将得到字符串“ bbaaegh”。我已经尝试过了,这给了我正确的字母,但是我无法将它们连接成一个字符串。
x <- 12384579
x.string <- str_c(letters[26 - as.numeric(strsplit(as.character(Reverse_number(x)), "")[[1]])])))
其中Reverse_number是以下函数:
Reverse_number <- function(x){
n <- trunc(log10(x)) # now many powers of 10 are we dealing with
x.rem <- x # the remaining numbers to be reversed
x.out <- 0 # stores the output
for(i in n:0){
x.out <- x.out + (x.rem %/% 10^i)*10^(n-i) # multiply and add
x.rem <- x.rem - (x.rem %/% 10^i)*10^i # multiply and subtract
}
return(x.out)
}
谢谢!
答案 0 :(得分:1)
# example number
x = 2211578
# get each character separately
y = as.numeric(unlist(strsplit(as.character(x), split="")))
# get corresponding letters and combine them
paste0(letters[y], collapse = "")
# [1] "bbaaegh"
您可以将以上内容用作功能:
GetLetterString = function(x) {paste0(letters[as.numeric(unlist(strsplit(as.character(x), split="")))], collapse = "")}
GetLetterString(2233)
# [1] "bbcc"
答案 1 :(得分:1)
设置您的号码进行转换
x <- 2211578
转换为字符向量并在每个字符上分割
str <- strsplit(as.character(x),"")[[1]]
转换回整数并选择相应的字母
str <- letters[strtoi(str)]
粘贴以创建单个字符串。
str <- paste0(str,collapse = "")
str
# [1] "bbaaegh"