[R] function design

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Tue Mar 19 00:28:40 CET 2002

Michaell Taylor <pols1oh at bestweb.net> writes:

> I have a, no doubt, simple question. I wish to write a function such
> that 
> a <- 9
> b <- 10
> changer _ function(x,y) { if (y>x){ x <<- Y+1}}

(something appears to be missing here?)
> Of course there are easier ways to accomplish the task above, but I am
> more interested in how to have the "x <<- Y+1" part of the function to
> change x in place for purposes of a much larger function.
> I have been wrestling with various forms of the assign, as.name,
> deparse, substitute (by now you probably sense a air of desperation)
> commands, and permuations thereof.

..although not with sufficient perseverance, I suggest. These matters
are tricky and you need to pay close attention to the details, but it
pays off in the longer run.

I think what you mean is something like this:

changer <- function(x,y) {
  xx <- substitute(x)
  if (y > x)
     eval.parent(substitute(x <- foo, list(foo=y + 1, x=xx)))


changer <- function(x,y) {
  xx <- deparse(substitute(x))
  if (y > x)
     assign(xx, y + 1, envir=parent.frame())

The tricky bit is that you cannot substitute the actual argument for x
after it gets evaluated for the  y > x condition.

(Note however that more often that not, this kind of stuff turns out
to be just a mental exercise, because there is a better way of doing
what you were trying to do originally!)

   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list