assigning lists elements as function arguments

南笙酒味 提交于 2019-12-24 07:08:07

问题


Suppose that:

list_a <- list(1, 10)
list_2 <- list(5, 20)

my.foo <- function (z,w) z+w 

My main question is: for each list_ object, how to pass its two elements as the arguments of my.foo so that to obtain 11 and 25?

My closest guess to solve the problem so far is:

mapply(my.foo, list_a, list_2)

but it is not suited for what I need to do, as it returns 6 and 30.

Thanks for any suggestions, Stefano


回答1:


You can use ls and get to get the objects and do.call to call your function with the content of the objects as arguments:

sapply(ls(pattern="list_*"), function(x) do.call(my.foo, get(x)))
# list_2 list_a 
#     25     11 

If you instead wanted to provide a list of objects to operate on:

objs <- list(list_a, list_2)
unlist(lapply(objs, function(x) do.call(my.foo, x)))
# [1] 11 25


来源:https://stackoverflow.com/questions/23170461/assigning-lists-elements-as-function-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!