Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of a functions inside a list

Tags:

r

What I wish to achieve

So I want to get the names of my function inside a list of function.

Here is an example:

foo = list(foo1 = sum, foo2 = mean)

What I wish to extract from foo is:

list("sum", "mean")

And I would like it to be a function, meaning:

> foo = list(foo1 = sum, foo2 = mean)
> super_function(foo)
list("sum", "mean")

What I have checked

Applying names:

> sapply(foo , names)
$`foo1`
NULL

$foo2
NULL

Applying deparse(substitute())

> my_f <- function(x)deparse(substitute(x))
> sapply(foo, my_f)
    foo1     foo2 
"X[[i]]" "X[[i]]" 

Neither idea works....

More background:

Here are some more details. One don't need them to understand the first question, but are extra details asked by community.

I'm using those functions as aggregation functions given by the user.

data(iris)
agg_function<-function(data, fun_to_apply){
  res <- list()
  for (col_to_transform in names(fun_to_apply)){
    res[col_to_transform] <- (fun_to_apply[[col_to_transform]])(data[[col_to_transform]])
  }
  res
}


agg_function(iris, fun_to_apply = list("Sepal.Length" = mean, "Petal.Length" = sum))

Result is:

$`Sepal.Length`
[1] 5.843333

$Petal.Length
[1] 563.7

In this example I'm performing aggregation on two columns of iris. But I wish to have the name of the performed function in the name of each field of my result. NB: This is an over simplification of what I'm doing;

Conclusion:

Do you have any ideas?

like image 532
Emmanuel-Lin Avatar asked Aug 01 '18 13:08

Emmanuel-Lin


1 Answers

If you are starting from just the list foo = list(foo1 = sum, foo2 = mean), then it's not possible. The call to list() will evaluate the parameters returning the values that the variables sum and mean point to but it will not remember those variable names. Functions don't have names in R. But functions can be assigned to variables. However in R functions can live without names as well.

You've basically just created a named list of function. That might also look like this

foo = list(foo1 = function(x) sum(x+1), 
    foo2 = function(x) mean(x+1))

Here we also have functions, but these functions don't have "names" other than the names you gave to them in the list.

This only chance you have of making this work is using something other than list() when creating foo in the first place. Or having them actually explicitly call list() in the function call (which isn't very practical).

like image 103
MrFlick Avatar answered Oct 19 '22 04:10

MrFlick