Optional, but recommended startup:

Change the file output to both html and md documents (not notebook).

Intro to dplyr syntax

  1. Load the gapminder and tidyverse packages. Hint: suppressPackageStartupMessages()!
    • This loads dplyr, too.
  2. knit the document.

select()

  1. Make a data frame containing the columns year, lifeExp, country from the gapminder data, in that order.

  2. Select all variables, from country to lifeExp.

  3. Select all variables, except lifeExp.

  4. Put continent first. Hint: use the everything() function.

  5. Rename continent to cont.

arrange()

  1. Order by year.

  2. Order by year, in descending order.

  3. Order by year, then by life expectancy.

Piping, %>%

Note: think of %>% as the word “then”!

  1. Combine select() Task 1 with arrange() Task 3.

filter()

  1. Only take data with population greater than 100 million.

  2. Of those, only take data from Asia.

git stuff (Optional)

Knit, commit, push!

Break/Challenge: metaprogramming

Here’s an activity for you to do during the break, in case you’re all caught up. It should help you understand metaprogramming a bit more.

Suppose you’re the instructor of an R programming course. You write an assignment question to evaluate whether students can write an if statement, for which an answer to the question looks something like this:

my_commute <- 60
if (my_commute > 30) {
    print("That's a long commute!")
} else {
    print("That's a short commute.")
}

Your task is to use metaprogramming to check whether a response (like the one above) works and contains an if statement. You should roughly follow these steps, using adv-r: expressions as a resource (especially Section 18.1).

  1. Wrap the above block of code in the expr() function from the rlang package.
  2. Use the eval() function to execute the code, to see if the code runs.
  3. Use the as.character() function to check whether this response contains an if statement.

Relational/Comparison and Logical Operators in R

  1. Find all entries of Canada and Algeria occuring in the ’60s.

  2. Find all entries of Canada, and entries of Algeria occuring in the ’60s.
  3. Find all entries not including Canada and Algeria.

Bonus Exercises

If there’s time remaining, we’ll practice with these three exercises. I’ll give you 1 minute for each, then we’ll go over the answer.

  1. Take all countries in Europe that have a GDP per capita greater than 10000, and select all variables except gdpPercap. (Hint: use -).

  2. Take the first three columns, and extract the names.

  3. Of the iris data frame, take all columns that start with the word “Petal”.
    • Hint: take a look at the “Select helpers” documentation by running the following code: ?tidyselect::select_helpers.
    • Exercise from r-exercises.
LS0tCnRpdGxlOiAnY20wMDU6IGBkcGx5cmAgRXhlcmNpc2U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