Skip to content
Prev 255893 / 398506 Next

IFELSE function XXXX

1<-data3$input1)

Avoid assignments in arguments to function calls, especially
multiple assignments to the same object, except when you know
what you are doing and want to write obscure code.

Change the above line to
  data3$input1 <- ifelse(data3$res1==1, data3$input1+10, data3input1)

There is nothing too special about ifelse here, you would get
similar results if you put assignment statements in other function
calls.  The assignment gets evaluated just as things like log(12)
or data3$input1+10 get evaulated when given as arguments.  E.g.,
  > x <- 1
  > cat(x <- 2:1, x <- 6:3, x <- 10:4, "\n")
  2 1 6 5 4 3 10 9 8 7 6 5 4
  > x
  [1] 10  9  8  7  6  5  4
Which version of x you end up with depends on which argument
the function evaluates last.
  > f <- function(arg1, arg2) arg2 + arg1
  > f( x <- 7, x <- 101 )
  [1] 108
  > x
  [1] 7

An example of obscure code involving multiple assignments
to one object is
  if (is.null(tms <- x$terms) && is.null(tms <- attr(x, "terms"))) {
     stop("Cannot find a list component or attribute called terms")
  }
  tms # x$terms if it exists, otherwise attr(x, "terms")
Since the order of evaluation of the 2 arguments to && is well
defined (left then right, and the right won't be evaluated unless
the left if TRUE), this produces a trustworthy answer.  Most functions
don't promise any particular order of evaluation.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com