質問

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top