关于运算符.&.与.|.的定义及功能咨询
Hey there! Great question—these two operators are niche but handy, and they’re most commonly associated with the R programming language. Let’s break down exactly what they do:
.&. and .|.? These are element-wise short-circuit logical operators—a less common but useful variation of R’s standard logical operators. Unlike R’s &&/|| (which only evaluate the first element of vectors) or &/| (which evaluate all elements without short-circuiting), .&. and .|. combine element-wise evaluation with short-circuit behavior.
.&. (Element-wise Short-circuit AND)
- Core Function: For each pair of elements across input vectors, it returns
TRUEonly if both elements areTRUE. The key twist is short-circuiting: if the first element in a pair isFALSE, it skips evaluating the second element entirely (since the result will beFALSEregardless). This saves computation time when the second expression is resource-heavy. - Example Comparison:
# Standard & evaluates all elements, even when first is FALSE c(FALSE, TRUE) & (print("Computed!"); c(TRUE, FALSE)) # Output: Prints "Computed!" twice, returns [1] FALSE FALSE # .&. short-circuits the first element pair c(FALSE, TRUE) .&. (print("Computed!"); c(TRUE, FALSE)) # Output: Prints "Computed!" once, returns [1] FALSE FALSE
.|. (Element-wise Short-circuit OR)
- Core Function: For each pair of elements across input vectors, it returns
TRUEif either element isTRUE. Again, short-circuiting applies here: if the first element in a pair isTRUE, it skips evaluating the second element (since the result will beTRUEregardless). - Example Comparison:
# Standard | evaluates all elements, even when first is TRUE c(TRUE, FALSE) | (print("Computed!"); c(TRUE, FALSE)) # Output: Prints "Computed!" twice, returns [1] TRUE FALSE # .|. short-circuits the first element pair c(TRUE, FALSE) .|. (print("Computed!"); c(TRUE, FALSE)) # Output: Prints "Computed!" once, returns [1] TRUE FALSE
Key Note
Keep in mind these operators aren’t universal across all languages—they’re specific to R (often used in tidyverse/rlang contexts). Don’t confuse them with R’s &&/||, which only check the first element of vectors and return a single boolean value, not an element-wise vector.
内容的提问来源于stack exchange,提问作者anonon

