Someone has solved my question applying list of functions on list of argument by order, now I have another similar question, how to apply function in the list my name? For example, if I have:
f1 <- function(x) {x}
f2 <- function(x) {2*x}
f3 <- function(x) {3*x}
fun_list <- list(good=f1, better=f2, best=f3)
arg_list <- list(better=1, best=2, good=3)
I want to get the list of functions called on their respective named parameter, i.e., I want:
some_magic_fun(fun_list, arg_list) == list(f1(3), f2(1), f3(2))
What would be good way to do it?
lapply() function in R Programming Language is used to apply a function over a list of elements. lapply() function is used with a list and performs the following operations: lapply(List, length): Returns the length of objects present in the list, List.
The apply() function lets us apply a function to the rows or columns of a matrix or data frame. This function takes matrix or data frame as an argument along with function and whether it has to be applied by row or column and returns the result in the form of a vector or array or list of values obtained.
14.1 Functions in RFunctions can be passed as arguments to other functions. This is very handy for the various apply functions, like lapply() and sapply() . Functions can be nested, so that you can define a function inside of another function.
The list data structure in R allows the user to store homogeneous (of the same type) or heterogeneous (of different types) R objects. Therefore, a list can contain objects of any type including lists themselves.
As I understand it you want to choose the functions and the arguments from lists not necessarily in order but that have a common set of names:
lapply(names(fun_list), function(n) fun_list[[n]](arg_list[[n]]) )
#----------
[[1]]
[1] 3
[[2]]
[1] 2
[[3]]
[1] 6
It wasn't entirely clear if you want the results but that was what I assumed. If you really wanted unevaluated expressions, you will need to clarify.
1) mapply This does not give a list (2 below does) but it may be what you really want:
> mapply(do.call, fun_list, lapply(arg_list[names(fun_list)], list))
good better best
3 2 6
2) Map This gives a list as the result which is what was asked for. Its the same as (1) except mapply
is replaced with Map
:
> Map(do.call, fun_list, lapply(arg_list[names(fun_list)], list))
$good
[1] 3
$better
[1] 2
$best
[1] 6
Revised based on comments.
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