Miscellaneous R Exercises

Author

Alasdair Warwick

Published

March 1, 2025

Setup

Exercises

dplyr Select vs Base R

Write the dplyr equivalent for selecting columns “Sepal.Length” and “Sepal.Width” from the iris dataset.

Hint

Use dplyr::select() to select specific columns.

iris |>
    select(Sepal.Length)
Fully worked solution:

Use select() to select the columns:

iris |>
    select(Sepal.Length, Sepal.Width)

dplyr Filter vs Base R

Write the dplyr equivalent for filtering rows where Sepal.Length is less than 5.

Hint

Use dplyr::filter() to filter rows based on a condition.

iris |>
    filter(Sepal.Length == 5)
Fully worked solution:

Use dplyr::filter() to filter the rows:

iris |>
    filter(Sepal.Length < 5)

dplyr Select and Filter vs Base R

Write the dplyr equivalent for selecting columns “Sepal.Length” and “Sepal.Width” from rows where Sepal.Length is less than 5.

Hint

Use dplyr::filter() and dplyr::select() together.

iris |>
    filter(Sepal.Length > 5) |>
    select(Sepal.Width)
Fully worked solution:

Use dplyr::filter() and dplyr::select() together:

iris |>
    filter(Sepal.Length < 5) |>
    select(Sepal.Length, Sepal.Width)

dplyr Pull vs Base R

Write the dplyr equivalent for pulling the Sepal.Length column from rows where Sepal.Length is less than 5.

Hint

Use dplyr::pull() to extract a single column.

iris |>
    filter(Sepal.Length >= 5) |>
    pull(Sepal.Width)
Fully worked solution:

Use dplyr::filter() and dplyr::pull() together:

iris |>
    filter(Sepal.Length < 5) |>
    pull(Sepal.Length)