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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With