Ali
Ali

Reputation: 9830

Pass ... argument to another function

I am writing a function foo(..., lev) on the base of makeContrasts function of package limma (of bioconductor):

makeContrasts(..., contrasts=NULL, levels)

I want to pass the ... argument of foo 'as-is' to makeContrasts. Here is my code:

foo = function(..., lev) {
    e = substitute(list(...))
    makeContrasts(e[[2]], levels=lev)
}

foo(a + b, design)

The reason I have used e[[2]] is that e will be list(a+b) and e[[1]] is list but e[[2]] is what I need: a + b

But the problem is that the actual argument passed to makeContrast is e[[2]] and not a + b. So what to do?

The complete parameter assignments are as below:

ct = factor(c("a","b"))
design = model.matrix(~0+ct)
colnames(design)=levels(ct)
makeContrasts(a+b,levels=design) # It works
foo(a+b, design) # Does not work

Upvotes: 2

Views: 650

Answers (4)

mnel
mnel

Reputation: 115382

A may be over simplifying the problem, but does the following not just work

foo = function(..., lev) {
 makeContrasts(...,levels =lev)
}

foo(a + b,b+c, lev =letters[1:3])


## Contrasts
## Levels a + b b + c
## a     1     0
## b     1     1
## c     0     1

using your example

I don't appear to be oversimplifying.

If ... contain the arguments to be passed to another function, then all you need is to pass ... to that function. ...

ct = factor(c("a","b"))
design = model.matrix(~0+ct)
colnames(design)=levels(ct)
makeContrasts(a+b,levels=design) 
## Contrasts
## Levels a + b
##  a     1
##  b     1
foo(a+b, lev = design)
## Contrasts
## Levels a + b
##  a     1
##  b     1

Upvotes: 1

IRTFM
IRTFM

Reputation: 263301

a=3, 
b="test"
 foo = function(...) {
    e = substitute(...)
     eval(e[[3]]) 
}

foo(a + b)

foo(a + b)
[1] "test"

As pointed out by others, your expectations remain unclear. Possibly you do not want evaluation and only want the symbol:

foo = function(...) {
    e = substitute(...); str( e[[3]])
    return(e[[3]]) 
}

foo(a + b)
# symbol b
#b

Upvotes: 0

Joshua Ulrich
Joshua Ulrich

Reputation: 176638

Seems like you simply need to remove the list call:

> foo <- function(...) f(substitute(...))
> f <- function(...) eval(...)
> a <- 1; b <- 3
> foo(a+b)
[1] 4

Upvotes: 2

Bob
Bob

Reputation: 1

If you are trying to pass a + b as a string, add quotes. You could also set an object to be "a + b" and pass the object.

Upvotes: 0

Related Questions