Last active
November 19, 2020 15:23
-
-
Save alekrutkowski/fd72b232f1e54d708e3c07b49c3e85f3 to your computer and use it in GitHub Desktop.
Convert Excel column letter codes to numbers (inverse of `openxlsx::int2col`)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Convert Excel column letter codes to numbers | |
| # Very similar to openxlsx::convertFromExcelRef() (see https://rdrr.io/cran/openxlsx/man/convertFromExcelRef.html). | |
| # The inverse function to openxlsx::int2col() (see https://rdrr.io/cran/openxlsx/man/int2col.html). | |
| # | |
| # excelColsToInt(c('a','F','x','aa','az','aaa','a','Az','aZ','AZ')) | |
| # #=> int [1:10] 1 6 24 27 52 703 1 52 52 52 | |
| # | |
| # x <- c('a','F','x','aa','az','aaa','a','Az','aZ','AZ') | |
| # n <- excelColsToInt(x) | |
| # x2 <- openxlsx::int2col(n) | |
| # identical(toupper(x),x2) | |
| # #=> TRUE | |
| excelColsToInt <- function(charvec) { | |
| charvec. <- toupper(charvec) | |
| lettersToNums <- function(x) { | |
| n <- which(LETTERS %in% x) | |
| if (length(n)==0) | |
| stop('`',x,'` is not a letter',call.=FALSE) | |
| n | |
| } | |
| chvToNums <- function(x) | |
| rev(tryCatch(sapply(x, lettersToNums, USE.NAMES=FALSE), | |
| error = function(e) | |
| stop('in `',x,'`\n',geterrmessage(), | |
| call.=FALSE))) | |
| nums <- lapply(strsplit(charvec.,""), chvToNums) | |
| expon <- function(x) seq_along(x)-1 | |
| colnum <- function(x) sum(x*26^expon(x)) | |
| as.integer(sapply(nums, colnum)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment