Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arguments

r

I have to 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 ?

like image 666
0x26res Avatar asked Apr 12 '11 11:04

0x26res


1 Answers

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 
like image 139
Joris Meys Avatar answered Sep 23 '22 07:09

Joris Meys