【问题标题】:Difference between the following two codes以下两个代码的区别
【发布时间】:2013-07-01 10:54:39
【问题描述】:

我有一个名为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

我的问题是为什么在第一个代码中所有元素都被使用了?

【问题讨论】:

标签: r loops if-statement for-loop


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-01-15
    • 2013-12-03
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 2014-03-21
    • 2018-06-12
    相关资源
    最近更新 更多