使用逻辑或在列表中组合逻辑向量 [英] Combine logical vectors in list using logical OR

查看:41
本文介绍了使用逻辑或在列表中组合逻辑向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我如何使用带有逻辑 OR ( | )的元素逐个比较有效地组合整个列表中的逻辑向量.结果应为长度与输入向量相同的逻辑向量.如果输入值的 any TRUE ,则结果为 TRUE ,否则结果为 FALSE .

示例

我有一个列表选项,其中包含一组长度相同的逻辑向量.

 >str(opts)清单5$ option1:logi [1:608247]否否否否否否否...$ option2:logi [1:608247]否是否是是是...$ option3:logi [1:608247]假真假假真假...$ option4:logi [1:608247]否否否否否否否... 

因此,我希望这样做:

  logi [1:608247]否是否是是是... 

因此,结果的第一个值 FALSE 是因为在所有向量的第一个位置的第一个位置 no TRUE 列表.结果的第二个值 TRUE 是因为都是两个(至少一个 any ) TRUE 在向量的第二个位置.

我可以将数据结构更改为 matrix data.frame 或其他更好的方法,我可以从 lapply .

解决方案

Reduce怎么样:

  Reduce(&",opts)Reduce("|",选择) 

Question

How do I effectively combine logical vectors across the list using elementwise comparisons with logical OR (|). The result should be a logical vector of same length as the input vectors. If any of the input values is TRUE, the result is TRUE, else the result is FALSE.

Example

I have a list opts with a set of logical vectors of the same length.

> str(opts)
List of 5
 $ option1: logi [1:608247] FALSE FALSE FALSE FALSE FALSE FALSE ...
 $ option2: logi [1:608247] FALSE TRUE  FALSE TRUE  TRUE  TRUE  ...
 $ option3: logi [1:608247] FALSE TRUE  FALSE FALSE TRUE  FALSE ...
 $ option4: logi [1:608247] FALSE FALSE FALSE FALSE FALSE FALSE ...

and I want this as a result:

logi [1:608247] FALSE TRUE FALSE TRUE TRUE TRUE ...

Thus, the first value of the result, FALSE, is because the are no TRUE in the first position across all vectors of the list. The second value of the result, TRUE, is because the are two (at least one, any) TRUE in the second position of the vectors.

I am fine with changing my datastructure to be a matrix or data.frame or something else if it is better I just get this from a lapply.

解决方案

How about Reduce:

Reduce("&", opts)
Reduce("|", opts)

这篇关于使用逻辑或在列表中组合逻辑向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆