将列表元素分配为函数参数 [英] assigning lists elements as function arguments

查看:58
本文介绍了将列表元素分配为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设:

  list_a<-list(1,10)list_2<-list(5,20)my.foo<-函数(z,w)z + w 

我的主要问题是:对于每个 list _ 对象,如何将其两个元素作为 my.foo 的参数传递,以便获得11和25?>

到目前为止,我最想解决该问题的猜测是:

  mapply(my.foo,list_a,list_2) 

但它不适合我需要做的事情,因为它返回6和30.

感谢您的任何建议,斯特凡诺

解决方案

您可以使用 ls get 来获取对象和 do.call 以对象的内容作为参数来调用函数:

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

如果您想提供要操作的对象列表:

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

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

解决方案

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

这篇关于将列表元素分配为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆