【发布时间】:2020-11-25 23:11:53
【问题描述】:
我想写一个函数来将excel的列名转换成相应的数字。到目前为止,我想出的只是部分起作用。也就是说,小写字母在前的输入(“AB”、“AC”等)工作正常。但反过来就不行了(“BA”、“CA”等)。我已经追踪了y <- which(base::LETTERS==x) 行出错,但我不太明白这些布尔运算符如何处理向量。有什么建议吗?
#so to pass excel column-names directly, this function should do the trick
LettersToNumbers <- function(input){
x <- toupper(substring(input, c(1:nchar(input)), c(1:nchar(input)))) #parse input-string
y <- which(base::LETTERS==x) #letters to numbers
y <- rev(y) #reverse
#base26 conversion:
result <- 0
for (i in 1:length(y)){
result <- result + ( y[i]*26^(i-1) )
}
return(result)
}
实际上,事实证明还有一些无效的示例。这里有一些,我不太明白发生了什么。
> which(LETTERS==c("A", "B"))
[1] 1 2
> which(LETTERS==c("A", "C"))
[1] 1
> which(LETTERS==c("A", "D"))
[1] 1 4
> which(LETTERS==c("D", "A"))
integer(0)
>
【问题讨论】:
-
你看到的是矢量回收;看看你会得到什么:which(LETTERS==c("A","B","C"))
-
反函数在我的回答here.