---
title: "Apply and Dates"
author: "Prof. Eric A. Suess"
date: "10/03/2018"
output:
  word_document: default
  pdf_document: default
  html_notebook: default
---

# Apply and Dates

Some examples from Chapter 5

### apply

```{r message = FALSE}
library(tidyverse)
library(Lahman)

Teams %>% select(15:40) %>%
  apply(MARGIN = 2, FUN = mean, na.rm = TRUE)
```

### lapply and sapply

```{r}
angles <- Teams %>%
  filter(franchID == "ANA") %>%
  group_by(teamID, name) %>%
  summarize(began = first(yearID), ended = last(yearID)) %>%
  arrange(began)
angles
```

```{r}
angles_names <- angles$name
angles_names

nchar(angles_names[1])
nchar(angles_names[2])
nchar(angles_names[3])
nchar(angles_names[4])
```

```{r}
lapply(angles_names, FUN = nchar)
```

```{r}
sapply(angles_names, FUN = nchar)
```

### Example of a function used with lapply

```{r}
top5 <- function(x, teamnames) {
  x %>% filter(name == teamnames) %>%
    select(teamID, yearID, W, L, name) %>%
    arrange(desc(W)) %>%
    head(n = 5)
}

angles_list <- lapply(angles_names, FUN = top5, x = Teams)
angles_list

```

### Dates

```{r}
library(mdsr)

OrdwayBirds

OrdwayBirds %>% select(Timestamp, Year, Month, Day) %>%
  glimpse()
```

covert to numbers

```{r}
OrdwayBirds <- OrdwayBirds %>% 
  mutate(Month= parse_number(Month), Year = parse_number(Year), Day = parse_number(Day))

OrdwayBirds %>% select(Timestamp, Year, Month, Day) %>%
  glimpse()

```

convert Timestamp

```{r}
library(lubridate)

WhenAndWho <- OrdwayBirds %>%
  mutate(When = mdy_hms(Timestamp)) %>%
  select(Timestamp, Year, Month, Day, When, DataEntryPerson) %>%
  glimpse()
```

```{r}
WhenAndWho %>% ggplot(aes(x = When, y = DataEntryPerson)) +
  geom_point(alpha = 0.1, position = "jitter")
```


```{r}
WhenAndWho %>% group_by(DataEntryPerson) %>%
  summarize(start = first(When), finish = last(When)) %>%
  mutate( duration = interval(start, finish) / ddays(1) )
```


```{r}
now()

as.Date(now())

today()

as.Date(today())

as.Date(now()) - as.Date(today())
```

How many days have you woken up in the morning?  Change the date.

```{r}
as.Date(today()) - as.Date("01/01/1970")
```

