gpt4 book ai didi

r - 将整数序列 1, 2, 3, ... 转换为相应的字符串序列 A, B, C,

转载 作者:行者123 更新时间:2023-12-04 06:15:59 24 4
gpt4 key购买 nike

将整数 1 到 N 转换为相应长度的字符串“A”、“B”、...“Z”、“AA”、“AB”...的快速、可扩展的方法是什么?

或者,我很乐意将整数向量映射到字符向量上,这样字符向量的每个元素都具有相同数量的字符。例如。 1, 2, ... 27 => "AA", "AB", ..., "AZ", "BA"

示例输入:

num_vec <- seq(1, 1000)
char_vec <- ???

更新

我的骇人听闻但最好的工作尝试:
library(data.table)
myfunc <- function(n){
if(n <= 26){
dt <- CJ(LETTERS)[, Result := paste0(V1)]
} else if(n <= 26^2){
dt <- CJ(LETTERS, LETTERS)[, Result := paste0(V1, V2)]
} else if(n <= 26^3){
dt <- CJ(LETTERS, LETTERS, LETTERS)[, Result := paste0(V1, V2, V3)]
} else if(n <= 26^4){
dt <- CJ(LETTERS, LETTERS, LETTERS, LETTERS)[, Result := paste0(V1, V2, V3, V4)]
} else if(n <= 26^5){
dt <- CJ(LETTERS, LETTERS, LETTERS, LETTERS, LETTERS)[, Result := paste0(V1, V2, V3, V4, V5)]
} else if(n <= 26^6){
dt <- CJ(LETTERS, LETTERS, LETTERS, LETTERS, LETTERS, LETTERS)[, Result := paste0(V1, V2, V3, V4, V5, V6)]
} else{
stop("n too large")
}

return(dt$Result[1:n])
}

myfunc(10)

最佳答案

评论中已经发布了几个不错的解决方案。只有@Gregor 发布的解决方案 here目前正在提供 Ben 的首选解决方案。

但是,@eddi、@DavidArenburg 和@G.Grothendieck 发布的方法也可以调整以获得首选结果:

# adaptation of @eddi's method:
library(data.table)
n <- 29
sz <- ceiling(log(n)/log(26))
do.call(CJ, replicate(sz, c("", LETTERS), simplify = F))[-1, unique(Reduce(paste0, .SD))][1:n]

# adaptation of @DavidArenburg's method:
n <- 29
list(LETTERS, c(LETTERS, do.call(CJ, replicate((n - 1) %/% 26 + 1, LETTERS, simplify = FALSE))[, do.call(paste0, .SD)][1:(n-26)])[[(n>26)+1]]

# adaptation of @G.Grothendieck's method:
n <- 29
sz <- ceiling(log(n)/log(26))
g <- expand.grid(c('',LETTERS), rep(LETTERS, (sz-1)))
g <- g[order(g$Var1),]
do.call(paste0, g)[1:n]

所有三个结果:
 [1] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"  "K"  "L"  "M"  "N"  "O" 
[16] "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" "AA" "AB" "AC"

关于r - 将整数序列 1, 2, 3, ... 转换为相应的字符串序列 A, B, C,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39731762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com