Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting a function call name from a function call

Tags:

function

r

call

Does anyone know how to write a function F which takes a function call (say, mean(x = 1:10)) as an argument, and returns just the name of the function being invoked (mean)?

My best attempts so far are summarised below

(function(x1){

    return(deparse(substitute(x1)))

})(mean(x = 1:10))
### 'mean(x = 1:10)' 

Changing x1 (the function call) to an expression before de-parsing doesn't seem to help much: that returns

(function(x1){

    return(deparse(as.expression(substitute(x1))))

})(mean(x = 1:10))
# "expression(mean(x = 1:10))"

If at all possible, I'd like to be able to use anonymous functions as an argument too, so F should return (function(x) print (x)) for (function(x) print (x))(1). If you need any clarification feel free to comment. Thanks.

edit1: just to note, I'd like to avoid checking for the first parenthesis and excising the the code before it (for "mean(x = 1:10)" that would return "mean"), as "bad(Fun_nAme" is actually a legal function name in R.

Question Answered: Josh O'Brien's answer was perfect: the function F that satisfies the above conditions is

F <- function(x) deparse(substitute(x)[[1]])

It works nicely for binary operators, standard functions and anonymous functions.

like image 331
Róisín Grannell Avatar asked Sep 03 '12 19:09

Róisín Grannell


2 Answers

Here's a simple function that does what you want:

F <- function(x) deparse(substitute(x)[[1]])

F(mean(x=1:10))
# [1] "mean"

F((function(x) print (x))(1))
# [1] "(function(x) print(x))"

F(9+7)
# [1] "+"
like image 139
Josh O'Brien Avatar answered Sep 20 '22 23:09

Josh O'Brien


I don't know what you're trying to do or if it's a good idea or if this is what you want but here's a whack at it with regex:

FUN <- function(x1){
    z <- deparse(substitute(x1))
    list(fun=strsplit(z, "\\(")[[c(1, 1)]],
    eval=x1)
}

FUN(mean(x = 1:10))
like image 21
Tyler Rinker Avatar answered Sep 18 '22 23:09

Tyler Rinker