3

我有一个大小为 5 的向量,例如:

 a<-c(1,4,6,3,2)

我还有另一个大小为 1 的向量:

 b<-9

我想写以下 if 条件:

if (a>b) { 1
}
else 0
}

我收到以下警告:

 Warning message:
In if (fitness_neighbours > user_fitness) { :
  the condition has length > 1 and only the first element will be used

我真正想做的是检查“a”中的任何元素是否满足条件。

4

3 回答 3

6

使用any()和比较:

if(any(a > b)) {
  # Executes if any value in a > b.
} else {
  # No a is greater than b.
} 

另一种使用方法pmax()

if (any(pmax(a, b) == a)) {

} else {

} 

这就是说,如果 ( a, b) 的任何最大值等于 中的值a,则a必须更大。

于 2013-01-09T10:30:58.287 回答
3

只需使用简单的比较:

a <- c(1,4,6,3,20)
b <- 9
a > b

[1] FALSE FALSE FALSE FALSE  TRUE

这是因为 R 本质上是一种基于向量的语言。

您可以轻松地将逻辑结果转换为数字:

as.numeric(a > b)
[1] 0 0 0 0 1
于 2013-01-09T10:29:54.777 回答
0

如果问题是任何值是否满足条件:

any(a>b)  # no need for `if`

如果这需要为 1/0,那么这些中的任何一个都可以工作:

as.numeric( any(a>b) )
c(0,1)[1+any(a>b)] # because indexing has origin at 1 rather than 0-based indexing

如果目标是选择满意的,请使用逻辑索引

a[ a>b ]

如果您想根据逐个元素的决定以“平行”方式选择其他两个向量中的两个元素中的哪一个,那么使用ifelse而不是if (){ }else{ }

ifelse( a>b, 1:5, seq(2,10, by=2) )
# returns 2 4 6 8 10
于 2013-01-09T11:16:28.870 回答