[R] An argument processing puzzle.

Duncan Murdoch murdoch at stats.uwo.ca
Mon Jan 18 23:25:06 CET 2010


On 18/01/2010 3:22 PM, Rolf Turner wrote:
> I have been trying to write a function mv(a,b) to move an
> object a to object b.  It returns no value, but only
> exists for this side effect.  Basically it just does
> b <- a; rm(a).  With some checking and prompting about
> over-writing.
> 
> The thing is, I'd like to be able to use either call by
> name or call by value syntax.  I.e. I want to set up my
> argument processing so that
> 
> 	mv(a,b)
> 	mv("a",b)
> 	mv(a,"b")
> 	mv("a","b")
> 
> are all equivalent.  I thought I had achieved this using
> 
>      anm <- if(is.character(substitute(a))) a else deparse(substitute 
> (a))
>      bnm <- if(is.character(substitute(b))) b else deparse(substitute 
> (b))
> 
> and then working with ``anm'' and ``bnm''.
> 
> However the real reason I wanted to be able to use text strings
> rather than names as arguments was so that I could do things like
> 
> 	mv(paste("x",i,sep="."),paste("y",i,sep="."))
> 
> (and use such a structure in a for loop, and so forth).
> 
> With the paste construction I seem to have to do something like putting
> in an ``eval'', as in eval(substitute(a)).  But then the whole thing
> falls over when a is a name, i.e. mv(a,b) doesn't work any more.
> 
> Is there an incantation that will allow me to accomplish all of my
> desiderata?

I doubt it.  How could you tell what a user intended who typed this?

name1 <- "a"
name2 <- "b"
mv(name1, name2)

What I'd suggest you do instead is to have 4 arguments, not just 2, e.g.

mv <- function(x, y, namex, namey)

and use

mv(a,b)
mv(namex="a", b)
mv(a, namey="b")
mv(namex="a", namey="b")

This is tricky enough in that in the second case, b will end up bound to 
the x argument, not the y argument, but some fiddly logic should be able 
to untangle that.

Duncan Murdoch



More information about the R-help mailing list