---
title:
output:
  revealjs::revealjs_presentation:
    theme: white
    css: white-edits.css
    highlight: tango
    transition: slide
    self_contained: false
    reveal_plugins: ["chalkboard","search"]
    transitionSpead: fast
    mathjax: "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS_SVG"
    reveal_options:
      minScale: 1.0
      maxScale: 1.0
      width: 1536
      height: 864
      slideNumber: true
      controlsTutorial: true
      chalkboard:
        theme: whiteboard
        readOnly: false
---


## ACCT 420: About you {data-background="../Backgrounds/title.jpg" class="header no-toc-progress" data-state="no-toc-progress"}

<!-- "reveal_plugins:..." and "chalkboard:" are handled by prep.py -->

<h3 class="date"><br>Session 2</h3>
<h2 class="author"><br>Dr. Richard M. Crowley</h2>

<!-- Load in primary data set -->
```{r, include=FALSE, message=F}
library(tidyverse)
library(magrittr)
df <- read.csv("../../Data/About you (Responses) - Form Responses 1-Edit.csv") %>%
  rename(country_name=Where.did.you.grow.up...country.or.region.,
         cafe=What.is.your.favorite.cafe..coffee.shop..tea.shop..etc....N.A.if.you.don.t.have.one.)
ll <- read_tsv("../../Data/countries_latlon.csv") %>%
  rename(country_name=name)
df %<>% left_join(ll)
```

## Where you are from {data-background="../Backgrounds/default.jpg" class="default"}

```{r, message=F, echo=F}
library(leaflet)
leaflet(df) %>%
  setView(lng = 103.8198, lat = 1.3521, zoom = 1) %>%
  addTiles() %>%
  addMarkers(lng = ~longitude, lat = ~latitude, clusterOptions = markerClusterOptions(), label=~country_name)
  
```


## Favorite cafe {data-background="../Backgrounds/default.jpg" class="default"}

```{r, echo=F, include=F}
# Note: The below code only works when run at SMU
library(jsonlite)
soa_ll <- c(1.2956192, 103.8498277)
find_cafe_ll <- function(coord_ll, radius, keyword) {
  # setup
  coord <- paste(coord_ll[1],coord_ll[2],sep=",")
  baseurl <- "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?"
  # You'll need your own API key on Google Cloud to replicate this.
  # The good news is that the first $200 USD in charges are waived per month.
  api_key <- readRDS('google_maps_api_key.rds')
  
  # query
  q <- paste(baseurl,"input=", URLencode(keyword),"&inputtype=textquery","&locationbias=circle:",radius,"@",coord,"&fields=formatted_address,name,rating,geometry,place_id","&key=",api_key, sep="")

  #print(q)
  
  # GET data
  data1<-fromJSON(q)
  
  # Check if found
  if (data1$status == "ZERO_RESULTS") {
    return(NULL)
  }
  
  # Return as a data.frame
  df_return <- data.frame(cafe=keyword,
                          cafe_name=data1$candidates$name,
                          lat=data1$candidates$geometry$location$lat,
                          long=data1$candidates$geometry$location$lng,
                          place_id=data1$candidates$place_id,
                          address=data1$candidates$formatted_address,
                          rating=ifelse(is.null(data1$candidates$rating), NA, data1$candidates$rating))
  return(df_return)
}

cafes = unique(df$cafe)
cafes = cafes[cafes!="NA" & cafes!="N/A" & cafes != "na" & cafes != "n/a" & !is.na(cafes) & cafes != ""]

if(!file.exists("google_maps_query.rds")) {
  first = T
  for (cafe in cafes) {
    cafe_data <- find_cafe_ll(soa_ll,radius = 1000,cafe)
    if (!is.null(cafe_data)) {
      if (first) {
        df_cafe <- cafe_data
        first <- F
      } else {
        df_cafe <- rbind(df_cafe,cafe_data)
      }
    }
  }
  saveRDS(df_cafe,"google_maps_query.rds")
} else {
  df_cafe <- readRDS("google_maps_query.rds")
}
```


```{r, message=F, echo=F}
# Visualize Google maps data
df %>% left_join(df_cafe) %>%
  filter(!is.na(place_id)) %>%
  leaflet() %>%
  setView(lng = 103.8498277, lat = 1.2956192, zoom = 14) %>%
  addTiles() %>%
  addMarkers(lng = ~long, lat = ~lat, clusterOptions = markerClusterOptions(),
             label = ~paste0(cafe_name),
             popup = ~paste0('<div style="font-size:18px; padding:10px; line-height:20px">Query: ',cafe,
                             '<br><a href="https://www.google.com/maps/search/?api=1&query=Google&query_place_id=',place_id,'">Link on Gmaps</a>',
                             '<br>Rating on Gmaps: ',rating,
                             '<br>Address: ',address,'</div>'))
```

## What you like to do {data-background="../Backgrounds/default.jpg" class="default"}

```{r, echo=F, message=F}
library(waffle)
library(rlang)

output_waffle_gg = function(data, cut=3, title="", ...) {
  dots <- ensyms(...)
  data2 <- data %>%
    select(!!!dots) %>%  # This is a quosure.  
    unlist()
  data2 <- data.frame(cats=data2)
  data2 %<>%
    filter(cats != '') %>%
    group_by(cats) %>%
    mutate(count = n()) %>%
    slice(1) %>%
    ungroup()
  cut = 0
  cells_cut = 0
  while (nrow(data2) > 10) {
    cut <- cut + 1
    cells_cut = cells_cut + sum(filter(data2,count <= cut)$count)
    data2 %<>% filter(count > cut)
  }
  data2 %>%
    ggplot(aes(fill=cats, values=count)) +
    geom_waffle(color="white", n_rows=5, size=1.125) + 
    scale_x_discrete(expand=c(0,0)) +
    scale_y_discrete(expand=c(0,0)) + 
    ggthemes::scale_fill_tableau(name=NULL) + 
    labs(title=title, x = paste0("1 square is 1 response; Only responses with >",cut," (",cells_cut," items omitted)"))
}
```


```{r, echo=F}
df %>% output_waffle_gg(cut=2, "", Hobby.Norm1, Hobby.Norm2, Hobby.Norm3)
```

## What you look forward to {data-background="../Backgrounds/default.jpg" class="default"}

```{r, echo=F}
df %>% output_waffle_gg(3, "", Pro.Norm1, Pro.Norm2)
```

## What you *not* look forward to {data-background="../Backgrounds/default.jpg" class="default"}

```{r, echo=F}
df %>% output_waffle_gg(3, "", Con.Norm1)
```

## Review of feedback {data-background="../Backgrounds/default.jpg" class="default"}

> Note: I won't go over the feedback each week explicitly

<div class="clearfix">
<div class="left">
**What you like**

- R review
- The slides
- Discussion in class

</div>
<div class="right">
**What you didn't**

- N/A -- 0 non-blank responses to that questions
</div>
</div>

## Some other questions {data-background="../Backgrounds/default.jpg" class="default never"}

1. What format is the exam?
    - Written, not coding oriented except a small (<= 20%) portion
2. How can we take notes on the slides?
    - I always provide a PDF for this purpose
        - Available on both elearn and at <a href="https://rmc.link/acct420">rmc.link/acct420</a>
    - Check out software like Drawboard for annotating PDFs!

## Packages used for these slides {data-background="../Backgrounds/coding.jpg" class="default"}

- `package:jsonlite`
- `package:knitr`
- `package:leaflet`
- `package:magrittr`
- `package:revealjs`
- `package:rlang`
- `package:tidyverse`
- `package:waffle`