Contents
 
Introduction
To R

Logical Values

R enables you to compute with Boolean, or Logical variables. These take on either the value True or False. You can store them in objects just as you can numeric or character data. You can use conditional tests to generate these values:
> x <- 1:10
> gt5 <- x > 5
> gt5
> gt5
 [1]  FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
> x == 4
 [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
> gt3 <- x > 3
> gt3
 [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE

Logical operators

You can do `and' and `or' operations on vectors with `&' and `|':
> x > 2 & x < 7
 [1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE
> x < 2 | x >7
 [1] TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE

True and False as Numbers...

If you try and do anything numeric with logical values, R converts true to 1 and false to 0. This can be usefully employed to count the number of true values in a vector. Examples:
> x <- 1:10
> y <- x > 3
> y
 [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
> y*2
 [1] 0 0 0 2 2 2 2 2 2 2
> sum(y)                counts TRUEs in y
[1] 7

Contents