ABC*_*ABC 1 loops for-loop if-statement r
我有一个名为的数据帧newdata
.它有两列名为BONUS
和GENDER
.
当我写下面的代码时r
:
> newdata <- within(newdata,{
PROMOTION=ifelse(BONUS>=1500,1,0)})
Run Code Online (Sandbox Code Playgroud)
虽然我没有在这里使用循环,但是以下代码在没有循环的情况下不起作用.为什么?
> 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
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么在第一个代码中使用了所有元素?
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
Run Code Online (Sandbox Code Playgroud)