---
title: "Data Wrangling R"
author: "Prof. Eric A. Suess"
output:
  word_document: default
  html_document:
    df_print: paged
  pdf_document: default
  html_notebook: default
---

Some of the code from Chapter 4, Section 1.

In this chapter dplyr is introduced.  We will be using dplyr all year.

The main idea of data wrangling with dplyr are the 5 verbs. 

**select()**  # take a subset of columns

**filter()**  # take a subset of rows

**mutate()**  # add or modify existing columns

**arrange()**  # sort the rows

**summarize()**  # aggregate the data across rows

The dplyr package is part of the tidyverse.  We will install and load the tidyverse.

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

# Star Wars dataset

```{r}
data("starwars")
glimpse(starwars)
```

# select()

```{r}
starwars %>% select(name, species)
```

# filter()

```{r}
starwars %>% 
  filter(species == "Droid")
```

# select()

```{r}
starwars %>% 
  select(name, ends_with("color"))
```

# mutate()

```{r}
starwars %>% 
  mutate(name, bmi = mass / ((height / 100)  ^ 2)) %>%
  select(name:mass, bmi)
```

# arrange()

```{r}
starwars %>% 
  arrange(desc(mass))
```

# summarize()

```{r}
starwars %>%
  group_by(species) %>%
  summarise(
    n = n(),
    mass = mean(mass, na.rm = TRUE)
  ) %>%
  filter(n > 1)
```

# Questions

Develop the R code to answer the following questions.

1. How many films are in the dataset?
2. Are there more Droids or humans in the Star Wars movies?
3. Which of the Star Wars movies was Luke Skywalker in?
4. Pose a question and answer it by wrangling the starwars dataset.

# Presidential examples

Try out the code in Chapter 4 Section 1 using the presidential data set.

```{r}
presidential
```

## Star Wars API and R package

More Star Wars stuff you might find interesting.

- Check out the [Star Wars](https://www.starwars.com/) website.  
- Check out the Star Wars API [sawpi](https://swapi.co/).
- And check out the R package [rwars](https://github.com/Ironholds/rwars).

## rwars package

This is a package that connects to the [sawpi](https://swapi.co/) to pull data from the API.

If the package does not install from CRAN you can isntall it from github.

    library(devtools)
    install_github("ironholds/rwars")
    
    

```{r echo=TRUE}
library(rwars)

planet_schema <- get_planet_schema()
names(planet_schema)

```

## rwars package

Get an individual starship - an X-wing.

Hopefully it won't time out and will actually bring the data back.

```{r echo=TRUE}
x_wing <- get_starship(12)
x_wing
```

