library(gradethis)
library(learnr)
library(qsslearnr)
library(tidyverse)
tutorial_options(exercise.checker = gradethis::grade_learnr)
knitr::opts_chunk$set(echo = FALSE)
tut_reptitle <- "QSS Tidyverse Tutorial 0: Output Report"

Working with Data in tidyverse

You'll often need to access different parts of a data frame to use in other commands. For instance, maybe you want to take the mean of a column of the data frame or maybe you want to see all of the data for the 4th unit. Either way, we'll need to know how to subset the data frame.

Before subsetting...

Before introducing functions for subsetting, we will introduce the pipe operator to you. The pipe, %>% , is able to help you code in a much more interpretable way. It is able to pass the data set to the function that you are interested in using.

UNpop <- data.frame(
  year = seq(1950, 2010, by = 10),
  world.pop = c(2525779, 3026003, 3691173, 4449049, 5320817, 6127700, 6916183)
)

Exercise

# use the pipe (`%>%`) to pass UNpop to the summary function
UNpop %>%
  summary()
grade_this_code()

Subsetting a data frame (I)

To select a particular variable from the data frame, you can use the select() function. So mydata %>% select(myvar) will be a vector of just the myvar column of the mydata data frame.

Exercise

## print out the world.pop variable using select()
UNpop %>%
  select(world.pop) 
grade_this_code()

Subsetting a data frame (II)

The slice() function is an intuitive way to index rows by their locations in a data set. It allows you to work with rows with multiple useful arguments.

Exercise

## extract rows 5 through 7 and all variables
UNpop %>%
  slice(5:7)
grade_this_code()
## extract values 5 through 7 of the world.pop variable
UNpop %>%
  slice(5:7) %>%
  select(world.pop)
grade_this_code()

Subsetting a data frame (III)

To select a particular variable that meets specific conditions, you can use the filter() function.

Exercise

# use the filter() function to extract the observations 
UNpop %>%
  filter(year <= 1990)
grade_this_code()

Submit

submission_ui
submission_server()


mattblackwell/qsslearnr documentation built on Sept. 17, 2022, 6:25 p.m.