Extract function call name from function call

Does anyone know how to write a function F that takes a function call (e.g. mean (x = 1:10)) as an argument and returns only the name of the called function (average value)?

My best attempts so far are given below.

(function(x1){ return(deparse(substitute(x1))) })(mean(x = 1:10)) ### 'mean(x = 1:10)' 

Changing x1 (calling a function) before an expression before parsing doesn't seem to help much: returns

 (function(x1){ return(deparse(as.expression(substitute(x1)))) })(mean(x = 1:10)) # "expression(mean(x = 1:10))" 

If at all possible, I would also like to use anonymous functions as an argument, so F should return (function (x) print (x)) for (function (x) print (x)) (1). If you need any clarification, feel free to comment. Thank you

edit1: just to note, I would like not to check the first bracket and exclude the code in front of it (for "mean (x = 1:10)" that would return "mean") since "bad (Fun_nAme" is actually the name legal function in R.

Answer to the question: Josh O'Brien's answer was perfect: a function F satisfying the above conditions,

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

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

+6
source share
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] "+" 
+8
source

I do not know what you are trying to do, or if this is a good idea, or if this is what you want, but here is a blow with it with a regular expression:

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

Source: https://habr.com/ru/post/924472/


All Articles