1

i have a dataframe named as newdata. it has two columns named as BONUS and GENDER.

When i write the following code in r:

  > newdata <- within(newdata,{
                   PROMOTION=ifelse(BONUS>=1500,1,0)})

it works though i haven't used loop here but the following codes don't work without loop. Why?

 > add <- with(newdata,
             if(GENDER==F)sum(PROMOTION))

  Warning message:
  In if (GENDER == F) sum(PROMOTION) :
  the condition has length > 1 and only the first element will be used

My question is why in the first code all elements have been used?

ABC
  • 341
  • 3
  • 10
  • This has been asked before [here](http://stackoverflow.com/questions/17252905/else-if-vs-ifelse/17253069#17253069) – Metrics Jul 01 '13 at 12:00
  • [**This is a very interesting post on `if-else`**](http://stackoverflow.com/questions/16275149/does-ifelse-really-calculate-both-of-its-vectors-every-time-is-it-slow) , in case you're interested to know a bit more. – Arun Jul 01 '13 at 23:33

1 Answers1

5

ifelse is vectorized, but if is not. For example:

> x <- rbinom(20,1,.5)
> ifelse(x,TRUE,FALSE)
 [1]  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE
[13] FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE

> if(x) {TRUE} else {FALSE}
[1] TRUE
Warning message:
In if (x) { :
  the condition has length > 1 and only the first element will be used
Thomas
  • 43,637
  • 12
  • 109
  • 140