我有一个矢量 v
我想找到所有值在 4 到 7 之间的元素。
v = c(1:9)
# indices of elements with values larger than 4
which(v > 4)
# indices of elements with values smaller than 7
which(v < 7)
v>4
和 v<7
给出 boolean 向量,我想将其合并。我尝试了以下方法,但对我不起作用,...# combination?
matching = which(v>4 && v<7) # does not work
如何对两个 boolean 向量应用 boolean 运算,从而得到一个结果向量?
最佳答案
使用 &
而不是 &&
. R 与其他语言的不同之处在于 &
不是按位 and
,而是一个逻辑运算符。&&
只计算每个向量的第一个元素:
‘&’ 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.
见
?"&&"
更多细节。
关于r - 如何比较 R 中的 boolean 向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13305763/