[R] Passing parameter to a function

Luca Meyer lucam1968 at gmail.com
Mon Dec 20 20:02:49 CET 2010


Hi Duncan,

Yes, A and B are columns in D. Having said that I and trying to avoid 

tab(D$A,D$B)

and I would prefer:

tab(A,B)

Unfortunately the syntax you suggest is giving me the same error:

Error in eval(expr, envir, enclos) : object "A" not found

I have tried to add some deparse() but I have got the error over again. The last version I have tried:

function(x,y){
    z <- substitute(time ~ x + y, list(x = deparse(substitute(x)), y = deparse(substitute(y))))
    xtabs(z, data=D)

gives me another error:

Error in terms.formula(formula, data = data) : 
  formula models not valid in ExtractVars 

Any idea on how I should modify the function to make it work?

Thanks,
Luca


Il giorno 20/dic/2010, alle ore 19.28, Duncan Murdoch ha scritto:

> On 20/12/2010 1:13 PM, Luca Meyer wrote:
>> I am trying to pass a couple of variable names to a xtabs formula:
>> 
>> >  tab<- function(x,y){
>>     xtabs(time~x+y, data=D)
>> }
>> 
>> But when I run:
>> 
>> >  tab(A,B)
>> 
>> I get:
>> 
>> Error in eval(expr, envir, enclos) : object "A" not found
>> 
>> I am quite sure that there is some easy way out, but I have tried with different combinations of deparse(), substitute(), eval(), etc without success, can someone help?
> 
> I assume that A and B are columns in D?  If so, you could use
> 
> tab(D$A, D$B)
> 
> to get what you want.  If you really want tab(A,B) to work, you'll need to do messy work with substitute, e.g. in the tab function, something like
> 
> fla <- substitute(time ~ x + y, list(x = substitute(x), y = substitute(y))
> xtabs(fla, data=D)
> 
> Duncan Murdoch



More information about the R-help mailing list