为什么ifelse不处理复杂的测试条件(&&/&和||/|的区别)?

Why does ifelse not process complex test conditions (difference between && / & and || / |)?

所以假设我有以下内容:

library(zoo)
v <- read.zoo(data.frame(dt=as.Date('2011-01-01')+0:9, a=1:10, b=11:20, c=21:30), index.column = "dt")

为什么这样做:

ifelse(v$a > 5, 1, 0)

这行不通:

ifelse(v$a > 5 && v$a < 8, 1, 0)

ifelse 需要所有参数的长度相同。根据?ifelse

If yes or no are too short, their elements are recycled. yes will be evaluated if and only if any element of test is true, and analogously for no.

即。如果其中一个参数大于 1,而其他参数的长度为 1,它会循环使用其他参数以使长度相同。在第二种情况下,根据 `?"&&"

所有参数的长度都是 1

& 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.

v$a > 5 && v$a < 8 
#[1] FALSE  # length 1

v$a > 5 & v$a < 8
#2011-01-01 2011-01-02 2011-01-03 2011-01-04 2011-01-05 2011-01-06 2011-01-07 2011-01-08 2011-01-09 2011-01-10 
#     FALSE      FALSE      FALSE      FALSE      FALSE       TRUE       TRUE      FALSE      FALSE      FALSE 

所以,这里没有回收。相反,如果我们只使用 &,那么它会给出预期的输出

ifelse(v$a > 5 & v$a < 8, 1, 0)

另外,请注意 as.integerTRUE/FALSE 强制转换为二进制 1/0。所以,这里不需要ifelse

as.integer(v$a > 5)

as.integer(v$a > 5 & v$a < 8)