Skip to content
Prev 245478 / 398503 Next

Passing parameter to a function

You didn't show what you did, but Duncan's suggestion
works for me when it is in a function:
aExpr <- substitute(a)
    bExpr <- substitute(b)
    formula <- substitute(time ~ e1 + e2, list(e1 = aExpr, e2 = bExpr))
    xtabs(formula, data = D)
}
B
A    11  12  13
  1   7  24   0
  2   0  32 960
B
A    11  12  13
  1   7  24   0
  2   0  32 960

The main problem with f0() is that the call attribute of
xtabs' output is always xtabs(formula=formula, data=D).
If you want the formula expanded to its value you have to
do more tricks.  E.g., use call() and eval() to pass
some arguments by value and some by name:

f1 <- function (a, b) {
    aExpr <- substitute(a)
    bExpr <- substitute(b)
    formula <- substitute(time ~ e1 + e2, list(e1 = aExpr, e2 = bExpr))
    # pass formula by value and D by name
    theCall <- call("xtabs", formula, data = quote(D))
    # may have to use enclos= argument to get D from right place
    eval(theCall)
}

or use substitute a fourth time to patch up the call
attribute:

f2 <- function (a, b) {
    aExpr <- substitute(a)
    bExpr <- substitute(b)
    formula <- substitute(time ~ e1 + e2, list(e1 = aExpr, e2 = bExpr))
    retval <- xtabs(formula, data = D)
    attr(retval, "call") <- do.call("substitute", list(attr(retval, 
        "call"), list(formula = formula)))
    retval
}


  > z <- f2(A,B) # f0 does the same
  > attr(z, "call")
  xtabs(formula = time ~ A + B, data = D)
  > z
     B
  A    11  12  13
    1   7  24   0
    2   0  32 960
Look at what 'z' is in the above:
  > g <- 
  + function(x,y){
  +     z <- substitute(time ~ x + y, list(x = 
  +         deparse(substitute(x)), y = deparse(substitute(y))))
  +     z
  + }
  > print(g(A,B))
  time ~ "A" + "B"
The strings "A" and "B" don't make sense there.  They need
to be names (a.k.a. "symbols").  Remove the calls to deparse()
and it will work.


Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com