[R] IFELSE function XXXX

William Dunlap wdunlap at tibco.com
Tue Apr 5 23:09:59 CEST 2011


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Dan Abner
> Sent: Tuesday, April 05, 2011 12:58 PM
> To: r-help at r-project.org
> Subject: [R] IFELSE function XXXX
> 
> Hello everyone,
> 
> This IFELSE function call is not working properly. I do not 
> receive an error
> message, but the actions are not executed conditional as I 
> was hoping. Any
> assistance is appreciated.
> 
> set.seed(12345)
> res1<-rbinom(10000,1,.1)
> rdata3<-transform(data.frame(res1),input1=rnorm(10000,50,10))
> data3
> #inducing correlation between res1 & input1
> ifelse(data3$res1==1,data3$input1<-data3$input1+10,data3$input
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 


> data3
> 
> Thank you,
> 
> Dan
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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.
> 



More information about the R-help mailing list