【问题标题】:How do "If" statements evaluate input? Is it on the vector as a whole or on each part of the vector individually?“If”语句如何评估输入?它是在整个向量上还是在向量的每个部分上?
【发布时间】:2020-06-16 14:33:16
【问题描述】:
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?

【问题讨论】:

  • if 的矢量化形式是ifelse。参见例如 stackoverflow.com/questions/4042413/…stackoverflow.com/questions/43877429/…
  • 不确定这是否真的是您的问题。但是ifelse( ) 函数是矢量化的。试试ifelse(x %% 2 == 0,x,"Not even or real")
  • 试试那个条件:if(any(x %% 2 == 0) &amp; sum(is.na(x)) &lt; 1){ ...
  • 我明白了。因此,“if”实际上是用于评估单个条件。对于“向量化”的 if 形式,即单独评估向量的每个数字或部分的 if 语句,我应该使用 ifelse 或使用其他函数,如 any

标签: r if-statement


【解决方案1】:

正如 cmets 中提到的,ifelse()if() 的矢量化版本。你说得对,if() 用于评估单个条件 - 具体来说,它用于评估 first 条件(如果它提供了布尔向量输入)。

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() 等内容可用于将布尔向量折叠成单个布尔元素,以便与香草 if() 一起使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-17
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 2015-07-07
    相关资源
    最近更新 更多