3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【小ネタ】Rで関数を実行時に関数名を取得する方法

Posted at

複雑なコードを書いているときに、どの関数からの呼び出しか
いちいちprintに明記するのが面倒で、動的に関数の名前を取得できたらいいな、というとき用の備忘

つまり、実現したいことは次のようなスクリプトを書たら、f1()と出す

f1 <- function(){
  print(get_tihs_function_name())
}

f1()

これも素直に関数が用意されているわけじゃなさそうだったので、自作しとく。
sys.frames()sys.calls()をうまく使えばいけることがわかった。

なお、REPLでの実行とsourceでの実行で違いがあるので、両方対応するためにはちょっと工夫が必要

get_tihs_function_name <- function(){
  tmp_frames <- sys.frames()
  tmp_calls <- sys.calls() 
  
  function_name_ix <- -1
  for(i in seq_along(tmp_frames)){
    if(environmentName(tmp_frames[[i]]) == 'R_GlobalEnv'){
      function_name_ix <- i + 1
    }
  }
  
  this_function_name <- ''
  # REPLで実行するとR_GlobalEnvにたどり着かないはずだから、REPL実行用に分岐用意しとく
  if(function_name_ix >= 0){
    this_function_name <- as.character(tmp_calls[[function_name_ix]])
  }else{
    this_function_name <- as.character(tmp_calls[[1]])
  }
  
  this_function_name <- paste0(this_function_name, '()')
  
  return(this_function_name)
}

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?