[R] An argument processing puzzle.

Peter Ehlers ehlers at ucalgary.ca
Mon Jan 18 23:48:00 CET 2010


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?
> 
Rolf,
  are you just trying to turn the input into character?
If so, the following may help, but I'd be surprised if
there aren't plenty of situations where it won't work.
I ain't no guru.

g <- function(x){
   x <- substitute(x)
   if(is.name(x)) {
     xnm <- deparse(x)
   }
   else {
     if(is.language(x)) {
       xnm <- eval(x)
     }
     else xnm <- x
   }
   get(xnm)
}

u <- 1:5
v <- letters[1:5]
u.v <- 5:1

g(u)
g('u')
g(v)
g('v')
g(paste('u', 'v', sep='.'))

  -Peter Ehlers

> Thanks.
> 
>     cheers,
> 
>         Rolf Turner
> 
> 
> ######################################################################
> Attention:\ This e-mail message is privileged and confid...{{dropped:9}}
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 
> 

-- 
Peter Ehlers
University of Calgary
403.202.3921



More information about the R-help mailing list