Logical Operators


[Comparison operators | Logical operators | Control operators ]


Comparison Operators

The following are comparison operators, which compare values and produce T or F

Logical Operators

There also logical operators which are used for the operations and, or, and not . Logic operators are used in conjunction with comparison operators to evaluate more than one logical expression

& returs T only if both elements are T. | returns T if at least one of the elements is T. xor returns T when one expression is T and one is F. any returns T if al least one operand is T. all returns T only if all the operands are T.

For example:

> a1_rnorm(10)
> a2_rnorm(10)
> a3_rnorm(10)
> a1
 [1] -0.5226737  0.1538121  0.5067107 -1.1949326  1.1703560  0.5727244
 [7]  1.6033799 -0.3409546  1.1935098  0.7097916
> a2
 [1]  0.32427046 -0.29435117 -0.58552243  0.62340261  0.89508001 -0.01296344
 [7] -0.63364021 -1.30471722  0.48555500  1.01060020
> a3
 [1]  0.1475238  0.2752559  0.4734608 -0.6418527  0.3212558 -1.7949369
 [7] -0.7480513 -0.2866477  0.1113259 -1.5838942
> log1_(a1 log1
 [1] T F F T F F F F F T
> log2_(a1 log2
 [1] T T F T F F F T F F
> log1 & log2
 [1] T F F T F F F F F F
> log1 | log2
 [1] T T F T F F F T F T        
> log4_!log1
> log4
 [1] F T T F T T T T T F
> xor(log1,log2)
 [1] F T F F F F F T F T  
> any(T,F,F)
[1] T
> all(T,F,F)
[1] F       
Logical objects are coerced to numbers when used with functions that require numerical values. When this occurs, TRUE is equivalent to 1 and FALSE is equivalent to 0.

>  sum(T,F,F,T,T)
[1] 3

Control Operators

If the value of the first operand is TRUE, then && evaluates, and returns as its value, the second operand; otherwise it returns F.

Similarly, if the first operand of || is FALSE, then the second argument is evaluated and returned; otherwise, it returns T without evaluating its second operand.

For example,

> r
 [1]  5 59 63 55  8  2 38 49 12 33  2  1
>  if (all(r>0) && sum(log(r))>1) x<-sum(log(r))+1
[1] 31.814
>  if (all(r>3) && sum(log(r))>1) x<-sum(log(r))+1
NULL
> if (all(r>3) ||  sum(log(r))>1) x<-sum(log(r))+1
[1] 31.814         


Comments to: Miguel A. Arcones

Go to main homepage: