2013-07-01 2 views
1

나는 데이터 프레임이 newdata입니다. BONUSGENDER이라는 두 개의 열이 있습니다.다음 두 코드의 차이

은 내가 r에 다음 코드를 작성하는 경우 : 내가 여기에 루프를 사용하지 않은 있지만 다음 코드는 루프없이 작동하지 않습니다하지만

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

가 작동합니다. 왜?

> 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 

내 질문에 모든 요소가 사용 되었습니까?

+0

이이 전에 요청 된 [여기] (http://stackoverflow.com/questions/17252905/else-if-vs-ifelse/17253069#17253069는) – Metrics

+0

은 [**이 매우이다 흥미로운 게시물'if-else' **] (http://stackoverflow.com/questions/16275149/does-ifelse-really-calculate-both-of-its-vectors-every-time-is-it-slow) , 좀 더 알고 싶다면. – Arun

답변

5

ifelse은 벡터화되었지만 if은 그렇지 않습니다. 예를 들어 :

> 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 
+0

고맙습니다. – ABC