【问题标题】:Error on 'If condition'-the condition has length > 1 and only the first element will be used [duplicate]“如果条件”出错-条件的长度> 1,并且仅使用第一个元素[重复]
【发布时间】:2019-01-18 11:03:19
【问题描述】:

在数据框ad2中,如果成本值在上下之间,则制作一个新的数据框。 我尝试了以下方法:

if (ad2$Cost.x>=ad2$lower & ad2$Cost.x<=ad2$upper) {
  ad3<-ad2[ad2$Country,ad2$Brand, ad2$Year, ad2$BU219.x, ad2$Cost.x, ad2$Value.x, ad2$Optimized_point.x]
}

但是出现了这个错误

  the condition has length > 1 and only the first element will be used

【问题讨论】:

  • 如果您的目标是创建一个新的data.frame,其中包含成本值介于上限和下限之间的行,您可能想尝试ind &lt;- which(ad2$Cost.x&gt;=ad2$lower &amp; ad2$Cost.x&lt;=ad2$upper); ad3 &lt;- ad2[ind, ]
  • 不需要使用哪个,在这种情况下,ad3 =ad2$lower & ad2$Cost.x

标签: r dataframe if-statement


【解决方案1】:

如果您打印ad2$Cost.x&gt;=ad2$lower &amp; ad2$Cost.x&lt;=ad2$upper 的值,您可以看到多个布尔条件。这是因为在 R 中所有操作都是矢量化的。

例子:

> cc =c(T,F)
> if (cc) print(cc)
[1]  TRUE FALSE
Warning message:
In if (cc) print(cc) :
  the condition has length > 1 and only the first element will be used

所以使用所有或任何这样的功能:

> if (all(cc)) print(cc) #If all conditions are true
> if (any(cc)) print(cc)
[1]  TRUE FALSE

【讨论】:

    【解决方案2】:

    试试这个

    如果 (ad2$Cost.x>=ad2$lower & ad2$Cost.x

    【讨论】:

    • 您正在正确索引列,但会出现问题中提到的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多