Last active
August 29, 2015 14:28
-
-
Save datalove/c5c8f7a599c0ea012324 to your computer and use it in GitHub Desktop.
R function to convert excel column names ('Q','AD', etc) to numbers
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
xl_col_to_num <- function(column) { | |
# calc value for a letter given its position i | |
# eg for'CZ', C's contrib is 26^(1-1)*3 and Z's contrib is 26^(2-1)*26 | |
calc_pos_val <- function(x,i) 26^(i-1) * which(LETTERS == x) | |
# for a single column like 'CZ', calc each positional value and sum the total | |
single_col <- function(x) calc_pos_val %>% mapply(x, rev(seq_along(x)) ) %>% sum() | |
column %>% | |
toupper %>% | |
strsplit(NULL) %>% # split c('AA','AB') into list(c('A','A'),c('A','B')) | |
sapply(single_col) | |
} | |
xl_col_to_num('AAA') | |
xl_col_to_num(letters) | |
xl_col_to_num(c('X','Y','Z','AA','AB','AZ','BZ','CA','AAA','AAB')) | |
# another way to | |
# xl_col_to_num <- function(column) { | |
# | |
# parts <- strsplit(column, NULL) %>% unlist %>% rev() | |
# num <- 0 | |
# for(i in seq_along(parts)) { | |
# num <- num + 26^(i-1) * which(toupper(letters) == parts[i]) | |
# } | |
# num | |
# } | |
#sapply(toupper(letters), xl_col_to_num) | |
#xl_col_to_num('AAA') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment