r - “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的原因吗?
解决方案
正如评论中提到的,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()
。
推荐阅读
- javascript - .map() 内的 catch 块中未更新变量
- c# - 与取消同步等待的安全方法是什么?
- docker - 如何使用 minikube 将 nginx-ingress 绑定到公共 IP
- ubuntu - Windows 10 上的 wsl 在运行互操作性时未加载配置文件
- spring-boot - 如果 @ResponseBody 数据为空(无)或空 {},如何处理
- blender - Blender:多个动作 - 当我添加一个新的对象时,对象会移动
- android - Kotlin - 尝试通过点击从另一个应用程序打开一个应用程序
- asp.net-core-webapi - 即使请求正文中缺少属性,也会执行 .NET Core WebApi 操作
- r - 如何将此数据框转置为如下示例(从长到宽)?
- r - 在 ggplot 代码集中没有可见的图例,尽管它应该是