---
title: "Comparisons"
author: "JJB + Course"
date: "02/06/2019"
output:
   html_document:
     toc: true
     toc_float:
       collapsed: false
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# Comparisons

## Example: Logical Values

Values equivalent to `TRUE`
```{r true-values}
TRUE
T
1L
```

Values equivalent to FALSE
```{r false-values}
FALSE
F
0L
```

## Example: Performing Comparisons

Checking a value against another value.

```{r comparisons}
42 == 42             # Is 42 equal to 42? Yes or No?

42 != 32             # Is 42 not equal to 32? Yes or No?

12 < 38              # Is 12 less than 38? Yes or No?

12 > 38              # Is 12 greater than 38? Yes or No?

38 > 38              # Is 38 greater than 38? Yes or No?

38 >= 38             # Is 38 greater than or equal to 38? Yes or No?

c(3, 2, 1, -5) > 2   # Are values greater than 2? Yes or No?
```

## Example: Comparing Strings

We need not only focus on numeric entries. Instead, we can include checks on
`character` or `string` values. However, additional care is required when 
performing an equality check.

```{r comparing-strings}
"toad" == "princess"     # Is 'toad' equal to 'princess'? Yes (TRUE) or No (FALSE)?
```

```{r string-case-difference}
"toad" == "Toad"         # Is 'toad' equal to 'Toad'? Yes (TRUE) or No (FALSE)?

"toad" == "toad"        # Is 'toad' equal to 'toad'? Yes (TRUE) or No (FALSE)?
```

```{r string-in-op}
"toad" %in% c("princess", "toad", "chef")
```


### Example: Vectorized Comparison

```{r ex-block-comparison}
# Comparison of vectors
c(11, -3, 1, 2) >= c(5, -2, 9, 42)

# Comparison of vector
# to a single element
c(3, 2, 1, -5) < 2
```

### Example: Set Comparison

"Needle in the Haystack" problems

```{r}
2 %in% c(3, 2, 1, -5)  # Does 2 belong to any values? Yes or No?

2 %in% c(3, 1, -5)      # Does 2 belong to any values? Yes or No?

c(3, 1, -5) %in% 2      # Are elements in the vector equal to 2?
```


### Exercise: Single-value Comparisons

```{r ex-single-comparsion}
x = c(1,2,3,4)

x == 2

x != 2

x < 2

x > 2

x <= 2
x >= 2

x %in% 2
```

### Exercise: Multiple-value Comparisons

```{r ex-vectorization-comparsion}
x = c(1,2,3,4)
y = c(-1, 2, 6, 0)

x == y

x != y

x < y

x > y

x <= y
x >= y

x %in% y
```

### Exercise:

1. Create an indicator variable that checks to see if subjects are male. 
1. Count the number of **female** subjects.
    - Hint: See `sum()` and `!`.
    
```{r indicator-exercise}
subjects = c("Male", "Female", "Female", "Female", "Male")

male_indicator = subjects == "Male"

male_indicator

# Here we check multiple needles against "Male" e.g. haystack.
subjects %in% "Male"

```

```{r}
length(subjects) - sum(male_indicator)
```



# Logical Operators

## Example: AND

```{r and-comparison-true}
3 > 2 & 42 != 5
```

```{r and-comparison-true-v2}
3 > 2 & 5 < 1
```

## Example: AND Short-circuit logic

```{r and-short-circuit}
8 < 2 & 5 == 5
```


```{r and-short-circuit-stop}
8 < 2 && stop("See... We never reached this point!")
    # ^^ Disable vectorized comparison.
```

### Exercise: AND Truth Table


| X       | Y       | X & Y |
|---------|---------|-------|
| `TRUE`  | `FALSE` | _____ |
| `TRUE`  | `TRUE`  | _____ |
| `FALSE` | `TRUE`  | _____ |
| `FALSE` | `FALSE` | _____ |

## Example: OR 

```{r or-comparison}
10 < 9 | 1 == 1
```

## Example: OR short circuit

```{r or-comparison-short-circuit}
10 < 9 | 1 == 1
```

### Exercise: OR Truth Table

| X       | Y       | X | Y |
|---------|---------|-------|
| `TRUE`  | `FALSE` | _____ |
| `TRUE`  | `TRUE`  | _____ |
| `FALSE` | `TRUE`  | _____ |
| `FALSE` | `FALSE` | _____ |

## Example: XOR 

```{r xor-comparison}
xor(10 < 9 , 1 == 1)
```

```{r or-comparison-v2}
xor(15 > 12 , 25 != 13)
```

### Exercise: XOR Truth Table

| X       | Y       | xor(X, Y) |
|---------|---------|-----------|
| `TRUE`  | `FALSE` | _________ |
| `TRUE`  | `TRUE`  | _________ |
| `FALSE` | `TRUE`  | _________ |
| `FALSE` | `FALSE` | _________ |


### Exercise: Scenario Comparison

```{r scenario-comparison}
x = c(0, 0.5, 1.0, 1.5, 2.0)
x

y = 3*x - 2
y
```

Evaluate the data under each comparison:

- `x < 2`
- `y == 1`
- `!(x < 2 | y == 1)`

## Example: Vectorized vs. Scalar Operation

```{r vec-vs-scalar-and}
# Vectorized Form
# element-wise compares
c(TRUE, FALSE, TRUE) & c(TRUE, FALSE, FALSE)

# Scalar form
# Uses first element-only
c(TRUE, FALSE, TRUE) && c(TRUE, FALSE, FALSE)
                   # ^^ uses two & to assert that only 1 value is taken.
```

```{r vec-vs-scalar-or}
# Vectorized Form element-wise compares
c(TRUE, FALSE, TRUE) | c(TRUE, FALSE, FALSE)

# Scalar form uses first element-only
c(TRUE, FALSE, TRUE) || c(TRUE, FALSE, FALSE)
                   # ^^ uses two | to assert that only 1 value is taken.
```

## Example: Reducing Logicals

```{r}
# Equivalent to requiring at least one element is true
any(c(TRUE, FALSE))

any(c(FALSE, FALSE))

# Equivalent to requiring every element is true
all(c(TRUE, FALSE))

all(c(TRUE, TRUE))
```

# Filtering Observations

## Example: Logical Subsets

```{r logic-subset-explicit}
ex_vec = c(5, 3, -2, 42)
ex_vec[c(TRUE, FALSE, TRUE, TRUE)]
```

## Example: Filtering Observations

```{r logic-subset-broken-down}
ex_vec = c(5, 3, -2, 42)
select_indices = ex_vec < 4    # Are values less than 4?
ex_vec[select_indices]         # Retrieve all values less than 4
```

## Extra Example: Vector Subsets

As a reminder, please recall the following _four_ ways to select elements from
a vector.

```{r examples-my-vec}
# Create a vector
my_vec = c(6.1, 5.5, 5.2, 5.9)

# Retrieve _all_ data
my_vec[]

# First observation
my_vec[1]

# Remove the second observation:
my_vec[-2]

# Keep only the first two observations with integers:
my_vec[c(1, 2)]

# Keep only the first two observations with logicals:
my_vec[c(TRUE, TRUE, FALSE, FALSE)]

# Out of Bounds gives missingness
my_vec[5]

# Name our vectors
names(my_vec) = c("Billy", "Angela", "Melissa", "Trevor")

# Notice names appear
my_vec

# Extract Melissa's contents
my_vec["Melissa"]
```

### Exercise: Filter Weights

Change the following piece of code to retrieve subjects whose weight is **more than** 240.

```{r weight-filter}
weights = c(150, 220, 332, 250, 244, 185)

## Change this line from
# weights[weights < 180]
```

## Example: Finding Instances

Recall the `subject_heights` data set.

```{r construct-df}
subject_heights = data.frame(
  id     = c(1, 2, 3, 55),
  sex    = c("M", "F", "F", "M"),
  height = c(6.1, 5.5, 5.2, 5.9)
)
```

Let's retrieve the variable `sex`.

```{r retrieve-variable}
# Retrieve a variable
subject_heights$sex
```

Now, let's aim to find all the observations that have `"F"` in `sex`.

```{r find-instances-in-variable}
# Retrieve a variable and compare it to a value
subject_heights$sex == "F"
```

Finally, let's subset these cases.

```{r find-cases-female}
female_heights = subject_heights[subject_heights$sex == "F", ]
female_heights
```


## Example: Subsetting Observations

Alternatively, we could allow _R_ to handle the intermediary steps of selecting
the variable and handling the subset.

```{r subset-ops-intermediary-steps}
# Allow R to handle the intermediary steps
female_heights_v1 = subset(subject_heights, sex == "F")
```

```{r create-steps}
# Inject an intermediary step
female_heights_v2 = subject_heights[subject_heights$sex == "F",]
```

### Exercise: 

1. Select the `id` variable using a dollar sign ($)
1. Find all observations with an `id` above 2.
