LoginSignup
1
1

More than 5 years have passed since last update.

Excel の列名(A,B,C,...)を数(1,2,3,...)に変換する #rstatsj

Last updated at Posted at 2013-10-08

Excel でもらったデータの特定の列(例えば AA 列)を抜き出したかったんだけど、AA 列が何番目の列なのかいちいち数えるのが面倒くさかったので関数を作りました。
昔同じようなの作った記憶あるし、ググったらどこかにありそうではあるのだけれど、作った方が速いので適当に。
バグがあったら教えて下さい。
また、他にうまい方法がある場合なども教えていただければ幸いです。

ExcelColToNum
ExcelColToNum <- function(x) {
  if(missing(x)) stop("")
  if(!is.character(x)) stop("")
  split.char.list <- lapply(strsplit(x, ""), function(v) toupper(rev(v)))
  if(!all(sapply(split.char.list, function(v) all(v %in% LETTERS)))) stop("")
  list <- lapply(split.char.list, function(v) {
    sapply(v, function(c) which(c == LETTERS))
  })
  sapply(list, function(vec) {
    mul <- 26^(seq_along(vec)-1)
    sum(mul * vec)
  })
}
使用例
ExcelColToNum(c("A", "C", "Z", "AA", "AC"))
結果
[1]  1  3 26 27 29

追記

裏RjpWikiの人に添削頂きました。ありがとうございます。
http://blog.goo.ne.jp/r-de-r/e/94ce407c74a75b2f888a32a16dc8108a

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1