r - Getting the name of a function after it got called -


i have saved function called "type" in list "funlist" so

funlist <- list(type = function() {      funname <- ???      print(funname) # should return "type" } )  

in other parts of code call function never name instead position in list, e.g.:

funlist[[1]]() 

in reality function "type" of course way more complicated, there part in function body uses function's own name. how can retrieve name when call position? in other words, how can have last function call print "type".

a bit of hacky solution, idea here extract number match.call() , find corresponding function name names(funlist).

funlist <- list(   type = function() {      #     getfunname(match.call())   },   bob = function() {     # else     getfunname(match.call())   } )   getfunname <- function(call) {     names(funlist)[as.numeric(gsub(".*?([0-9]+)(.*)", "\\1", as.character(call)[1]))] } 

output:

> funlist[[1]]() [1] "type" > funlist[[2]]() [1] "bob" 

Comments