0

我有一个值向量,我想确定这个向量的哪些元素在某个区间内,哪些元素不是。

所以我做了以下事情:

vec <- ifelse( 1<va2<3, 1, 0);

但我收到一条错误消息:vec 中的意外'<' 所以我尝试了以下操作:

vec <- ifelse( 1<va2 && va2<3, 1, 0);

但它只给了我第一个价值。

那么如何让 ifelse 使用两个逻辑值,或者有其他选择吗?

谢谢。

4

1 回答 1

2

尝试使用&not&&进行元素比较,在对元素向量执行逻辑比较时应该使用它。

> va2 <- c(2,1,4,2,6,0,3)
> ifelse( 1<va2 & va2<3, 1, 0)
[1] 1 0 0 1 0 0 0

从帮助文件(请参阅 参考资料?"&")中,您可以找到以下内容:

& and && indicate logical AND and | and || indicate logical OR. The shorter
form performs elementwise comparisons in much the same way as arithmetic 
operators. The longer form evaluates left to right examining only the first 
element of each vector. Evaluation proceeds only until the result is determined.
The longer form is appropriate for programming control-flow and typically 
preferred in if clauses.
于 2013-07-17T08:36:56.323 回答