简体   繁体   English

如何执行按元素的控制流程?

[英]How to perform element-wise control flow?

I'd like to implement element-wise control flow. 我想实现按元素的控制流。 An example: 一个例子:

v1 = as.vector(c(1,2,3))
v2 = as.vector(c(3,2,1))
v3 = as.vector(c(0,0,1))
for (i in 1:len(c1)) {
    if (c1[i]>=2 && c2[i]<=2) {
         v3[i]=1        
    }
} 
# end result: v3 = [0,1,1]

The preferred vector form (which does not work and not efficient): 首选矢量形式(无效且无效):

if (c1 >=2 & c2 <= 2) { 
    v3 = 1
}

Note that 注意

v3 = c1 >=2 & c2 <= 2  # end result v3=[0,1,0] 

does not work because v3 is not supposed to change if the condition is FALSE. 不起作用,因为如果条件为FALSE,则v3不应更改。

What kind of vector syntax can I use to avoid the for loop? 我可以使用哪种矢量语法来避免for循环? Note that if c1[i] is FALSE, c2[i] will not be examined at all. 注意,如果c1 [i]为FALSE,则将完全不检查c2 [i]。

I think you're looking for ifelse , it's a vectorized if . 我认为您正在寻找ifelse ,它是ifelse if If your vectors are logical (eg, T or F), you don't need to test if they're equal to TRUE, they are already either TRUE or FALSE. 如果向量是逻辑的(例如T或F),则无需测试它们是否等于TRUE,它们已经是TRUE或FALSE。

c1 = as.logical(sample(c(0, 1), size = 5, replace = T))
c2 = as.logical(sample(c(0, 1), size = 5, replace = T))

c3 = ifelse(c1 & c2, "both are true", "at least one is false")

cbind(c1, c2, c3)

#      c1      c2      c3                     
# [1,] "TRUE"  "FALSE" "at least one is false"
# [2,] "FALSE" "FALSE" "at least one is false"
# [3,] "TRUE"  "TRUE"  "both are true"        
# [4,] "TRUE"  "TRUE"  "both are true"        
# [5,] "FALSE" "TRUE"  "at least one is false"

Edits: 编辑:

For your v example, you can do this: 对于您的v示例,您可以执行以下操作:

# no need to coerce vectors to vectors with as.vector()
v1 = c(1, 2, 3)
v2 = c(3, 2, 1)
v3 = c(0, 0, 1)

v3 = ifelse(v1 >= 2 & v2 <= 2, 1, v3)

If v1 is >= 2 and v2 <= 2, then 1, else return the original v3 value. 如果v1 > = 2并且v2 <= 2,则为1,否则返回原始v3值。

In your comments, you say this: 在您的评论中,您这样说:

The And is short circuited when as soon as it encounters one FALSE. 当And遇到一个FALSE时,它就会短路。 In this case, if c1[i] is FALSE, "#update" won't execute regardless of the value of c2[i]. 在这种情况下,如果c1 [i]为FALSE,则无论c2 [i]的值如何都不会执行“ #update”。

This is correct. 这是对的。 It's the meaning of the AND operator in computer science. 这是计算机科学中AND运算符的含义。 If you don't like this behavior, perhaps you're looking for OR, which is coded as | 如果您不喜欢这种行为,则可能是您在寻找OR,其编码为| (vectorized) or || (矢量化)或|| (single element) in R. (单个元素)在R中。

Why not just: 为什么不只是:

v <- c(TRUE,TRUE,FALSE,TRUE)
if (FALSE %in% v) { ## update }
if (TRUE %in% v) { ## update , etc, can negate v if nec'y }

Of course that won't coerce to logical, you'll need to as.logical, but I think does what you want... 当然,这不会强迫逻辑,您需要逻辑上,但是我认为您想要的是...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM