【发布时间】: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) & sum(is.na(x)) < 1){ ... -
我明白了。因此,“if”实际上是用于评估单个条件。对于“向量化”的 if 形式,即单独评估向量的每个数字或部分的 if 语句,我应该使用 ifelse 或使用其他函数,如 any
标签: r if-statement