Let’s have a quick review of material.
tidyverse
This assumes you have the package tidyverse
. Recall, what do you need to do if you do not have it?
Use the mtcars (it’s built in, no need to load) to run the following examples.
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)
Use the filter() function to subset only includes records for cars with 4 or 6 cylinders.
mtcars
filter(mtcars, cyl %in% c("4","6"))
Now rewrite that to use piping (%>%) and keep only the first five rows.
mtcars %>%
filter(cyl %in% c("4","6")) %>%
head(n = 5)
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())
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)
Let’s review the dplyr functions.