Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Last active December 9, 2023 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-dray/15772d7fe7803aaa3c358fd6418a4484 to your computer and use it in GitHub Desktop.
Save matt-dray/15772d7fe7803aaa3c358fd6418a4484 to your computer and use it in GitHub Desktop.
Convert a spreadsheet cell reference (A1) to row-column (1, 1) format (overengineered draft)
cr2rc <- function(cell_ref) {
ref_split <-
strsplit(cell_ref, "(?<=[[:alpha:]])(?=[[:digit:]])", perl = TRUE)[[1]]
if (length(ref_split) != 2) {
stop(
"You must supply a cell reference of 1 to 3 letters (the column reference) ",
"followed by a number (the row reference), like 'A1' or 'ABC100'.",
call. = FALSE
)
}
if (
!inherits(ref_split[1], "character") |
!inherits(type.convert(x = ref_split[2], as.is = TRUE), "integer")
) {
stop(
"The first part (the column reference) must be a string ",
"and the second must (the row reference) be an integer",
call. = FALSE
)
}
row_int <- as.integer(ref_split[2])
if (!inherits(row_int, "integer") & col_num > 0) {
stop("Row reference must be a positive integer", call. = FALSE)
}
col_lets <- toupper(strsplit(ref_split[1], "")[[1]])
col_vals <- unname(sapply(col_lets, function(let) which(LETTERS == let)))
if (length(col_vals) > 3) {
stop("The column reference must be three letters or fewer.", call. = FALSE)
}
col_num <- col_vals[1]
if (length(col_vals) == 2) {
col_num <- (col_vals[1] * 26) + col_vals[2]
}
if (length(col_vals) == 3) {
col_num <- (col_vals[1] * 26 * 26) + (col_vals[2] * 26) + col_vals[3]
}
col_int <- as.integer(col_num)
if (!inherits(col_int, "integer") & col_num > 0) {
stop("Column reference must be a positive integer", call. = FALSE)
}
c(col = col_int, row = row_int)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment