Tidyverse

Example

Let’s have a quick review of material.

Quiz

Run tidyverse

This assumes you have the package tidyverse. Recall, what do you need to do if you do not have it?

Data Wrangling Review

Exercise with Hint

Use the mtcars (it’s built in, no need to load) to run the following examples.

Head function

Modify the following code to limit the number of rows printed to 5:

mtcars
head(mtcars)

How would you modify this to look at the first 8 rows?

head(mtcars, n = 8)

Filter function

Use the filter() function to subset only includes records for cars with 4 or 6 cylinders.

mtcars
filter(mtcars, cyl %in% c("4","6"))

Piping

Now rewrite that to use piping (%>%) and keep only the first five rows.

mtcars %>% 
  filter(cyl %in% c("4","6")) %>%
  head(n = 5)

Group By

Next, using the piping operation, count the number of records by cylinder groups.

mtcars %>% 
  filter(cyl %in% c("4","6")) %>%
  group_by(cyl) %>%
  summarise(Count=n())

Count

An even simpler way to rewrite the previous code is to use the count() function.

For example:

filter(mtcars, cyl %in% c("4","6")) %>%
  count(cyl)

dplyr functions

Let’s review the dplyr functions.

Quiz