首页 > 解决方案 > “If”语句如何评估输入?它是在整个向量上还是在向量的每个部分上?

问题描述

x <- c(1:10)

only_even <- function(x){
  if(x %% 2 == 0 && is.na(x) < 1){
    return(x)
  }else{
    print("Not even or real")
  }
}
only_even(x)

退货

"Not even or real"

即使 X (1:10) 中显然有偶数。

x <- c(1:10)

only_even <- function(x){
  if(x %% 2 == 0){
    return(x)
  }else{
    print("Not even or real")
  }
}
only_even(x)

退货

Warning message:
In if (x%%2 == 0) { :
  the condition has length > 1 and only the first element will be used

IM 对这两个结果感到困惑。特别是第二个错误“条件长度> 1,仅使用第一个元素”。创建 if 语句时,它是否仅适用于整个向量/输入?而不是单独遍历每个值?这就是为什么我得到关于条件的错误长度> 1的原因吗?

标签: rif-statement

解决方案


正如评论中提到的,ifelse()if(). 您是对的,if()它用于评估单个条件 - 具体来说,它用于评估第一个条件(如果它提供了布尔向量输入)。

x <- 1:5
y <- rep(3, 5)

ifelse(x > y, "yes", "no")
## [1] "no"  "no"  "no"  "yes" "yes"

if(x > y) "yes" else "no"
## [1] "no"
## Warning message:
## In if (x > y) "yes" else "no" :
##  the condition has length > 1 and only the first element will be used

当然,诸如any(),之类的东西all()可用于将布尔向量折叠成单个布尔元素,以便与 vanilla 一起使用if()


推荐阅读