--- title: "Data Wrangling R" author: "Prof. Eric A. Suess" output: html_document --- 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/). **Discontinued** - And check out the R package [starwarsdb](https://github.com/gadenbuie/starwarsdb). ## starwarsdb package This is a package contains 9 data tables. ```{r} library(starwarsdb) data(package = "starwarsdb") schema ```