---
title: "Ch 12"
subtitle: "Conditional Transformations"
format: 
  html:
    code-fold: TRUE
toc: TRUE
theme: darkly
warning: FALSE
message: FALSE
---

## Conditional Transformations

1. `if_else()`

If you want to use one value when a condition is TRUE and another value when it’s FALSE, you can use `if_else()`

```{r}
#| eval: FALSE
if_else(condition, true, false)
```


The first argument, condition, is a logical vector. 
The second, true, gives the output when the condition is true.
The third, false, gives the output if the condition is false.

2. `case_when()`

Performs different computations for different conditions. 

It takes pairs that look like `condition` ~ `output`. 

`condition` must be a logical vector; when it’s TRUE, `output` will be used.

```{r}
library(tidyverse)
x <- c(-3:3, NA)
case_when(
  x == 0   ~ "0",
  x < 0    ~ "-ve", 
  x > 0    ~ "+ve",
  is.na(x) ~ "???"
)

```

```{r}
library(nycflights13)
  flights |> 
  mutate(
    status = case_when(
      is.na(arr_delay)      ~ "cancelled",
      arr_delay < -30       ~ "very early",
      arr_delay < -15       ~ "early",
      abs(arr_delay) <= 15  ~ "on time",
      arr_delay < 60        ~ "late",
      arr_delay < Inf       ~ "very late",
    ),
    .keep = "used"
  )
```

**Note that both if_else() and case_when() require compatible types in the output. If they’re not compatible, you’ll see errors**

```{r}
#| eval: FALSE
if_else(TRUE, "a", 1)

case_when(
  x < -1 ~ TRUE,  
  x > 0  ~ now()
)
```

## Logical vectors & strings

This returns a logical vector whenever `pattern` is found within `string`.  Note that `string` can be a vector.

```{r}
#| eval: FALSE
str_detect(string, pattern)
```


```{r}
# detect the presence of a string
zillow <- read.csv("~/Google Drive/Teaching/DAT309/Week9/Metro_mlp_uc_sfrcondo_sm_month.csv")

if_else(str_detect(
  zillow$StateName,"CA"),
  "Cali-oh!",
  zillow$StateName) |> 
  glimpse()
```

## Exercise 1.

A number is even if it’s divisible by two, which in R you can find out with x %% 2 == 0. Use this fact and if_else() to determine whether each number between 0 and 20 is even or odd.

```{r}
n <- 0:20
```

## Exercise 2. 

Given a vector of days like x <- c("Monday", "Saturday", "Wednesday"), use an ifelse() statement to label them as weekends or weekdays.

## Exercise 3.

Use ifelse() to compute the absolute value of a numeric vector called x.

## Exercise 4. 

Write a case_when() statement that uses the month and day columns from flights to label a selection of important US holidays (e.g., New Years Day, 4th of July, Thanksgiving, and Christmas). First create a logical column that is either TRUE or FALSE, and then create a character column that either gives the name of the holiday or is NA.

```{r}
flights |> 
  mutate(Holiday =
    case_when(
      month == 1 & day == 1 ~ "NewYearsDay",
      month == 7 & day == 4 ~ "4th of July"
    ), 
    .keep = "used"
    )
```

## usmap package

1. Load zillow data.

```{r}
# load zillow data

#0 
sell <- read.csv("http://euclid.nmu.edu/~joshthom/Teaching/DAT309/Week9/Metro_median_sale_price_uc_sfrcondo_sm_month.csv") |> janitor::clean_names()

list <- read.csv("http://euclid.nmu.edu/~joshthom/Teaching/DAT309/Week9/Metro_mlp_uc_sfrcondo_sm_month.csv") |> janitor::clean_names()

#1. rename x's with sell and list, respectively
sell <- sell |> rename_with(~gsub("x","sell_",.))
list <- list |> rename_with(~gsub("x","list_",.))


#2. use variable.names() and head() to note common variables

list |> variable.names() |> head()
sell |> variable.names() |> head()

#3. select non-redundant variables and the foreign key
list_s <- select(list, !c(2,3,4,5,6))


#4. join data [link](https://r4ds.hadley.nz/joins.html#sec-mutating-joins)
list_sell <- sell |> left_join(list_s)

#5. pivot to get plotable data
ls_df <- pivot_longer(list_sell,
                      cols = starts_with("sell"),
                      names_to = "sell_date",
                      values_to = "sell_price") |> 
        pivot_longer(
                      cols = starts_with("list"),
                      names_to = "list_date",
                      values_to = "list_price")



#6. change date entries to dates (dttm format)
ls_df <- mutate(ls_df,
       sell_date = as_datetime(gsub("sell_","",ls_df$sell_date)))
ls_df <- mutate(ls_df,
       list_date = as_datetime(gsub("list_","",ls_df$list_date)))

#6.5 
zillow <- ls_df
```

2. Grab the average `sell_price` for each state.

```{r}
z <- zillow |> group_by(state_name) |> summarize(m = mean(sell_price, na.rm = TRUE))

```

3. Add **fips** code to data

```{r}
library(usmap)
zz <- z |> mutate(fips = fips(state_name))
```

4. Replace the `NA` with 00

```{r}
zzz <- zz |> mutate(fips = if_else(is.na(fips),"00",fips))
```

5. Plot using `usmap`

```{r}
plot_usmap(data = zzz, values = "m", color = "red")
```

6. Improve the plot

```{r}
library(scales)
plot_usmap(data = zzz, 
           values = "m", 
           color = "red") + 
  scale_fill_gradient(
    labels= label_dollar(scale_cut = cut_long_scale())
    ) +
  theme(legend.position = "right") +
  labs(fill = "Dollars")

```



