r - 如何比较 R 中的 boolean 向量

标签 r vector comparison boolean boolean-operations

我有一个矢量 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>4v<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/

相关文章:

r - 在within()中使用向量和R中的替换函数(还涉及memisc)。

c++ - 如何将char vector 转换为stringstream

matlab - 如何在 MATLAB 中向量化交集核函数?

algorithm - 如何为 B2B 创建神奇的购物车?

检测 data.frame 中的列是否为 .POSIXct 的可靠方法

r - 使用table()在R中创建3个可变频率表

r - ggplot 图例 - 更改标签、顺序和标题

c# - C++ 中的 vector 类是否可以像 C# 中的字典类一样使用?

c# - 如何在目标阈值内简化图像停止运动

java - 具有嵌套对象的对象的两个实例与动态比较(选项/规则/参数)