6

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.

2 Answers 2

8

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] "+"
Sign up to request clarification or add additional context in comments.

Comments

1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.