开发者

Converting a list to a "two or more objects" argument in R

I have t开发者_开发百科o call a function in R that takes "2 or more objects" as an input, so the function definition is:

function(..., all = TRUE, <other named parameters>)

where ... is defined as 2 or more objects

The issue is I have is that my objects are in a list, and I am working with a different number of objects according to what I want to do. So if my list has 3 elements for example I would have to do:

function(list[[1]], list [[2]], list[[3]])

How can I do that generically, regardless of the number of element in my list ?


You can use do.call, as that takes a list of arguments and applies them on function. Eg for rbind :

X <- list(A=1:3,B=4:6,C=7:9)
do.call(rbind,X)

  [,1] [,2] [,3]
A    1    2    3
B    4    5    6
C    7    8    9

Mind you, if you need extra arguments, you should add them to the list as well. See eg :

X <- list(A=list(A1=1:2,A2=3:4),B=list(B1=5:6,B2=7:8))

do.call(c,X)      # Returns a list
do.call(c,X,recursive=TRUE)  # Gives an error
do.call(c,c(X,list(recursive=TRUE)))

A.A11 A.A12 A.A21 A.A22 B.B11 B.B12 B.B21 B.B22 
    1     2     3     4     5     6     7     8 


An example would be helpful, but I'm pretty sure you're looking for do.call:

do.call(function, c(list, list(all=TRUE, <other named parameters>)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜