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"
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 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) )
UNpop
data set to the summary
function.# use the pipe (`%>%`) to pass UNpop to the summary function
UNpop %>% summary()
grade_this_code()
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.
select()
function with the pipe (%>%
) to print out the world.pop
variable from the UNpop
data frame.## print out the world.pop variable using select()
UNpop %>% select(world.pop)
grade_this_code()
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.
slice()
function to extract and print rows 5 through 7 of the UNpop
data frame. Please note that even if the n
argument is unnamed, the code will still be valid and produce the same result. But please write the full argument in this exercise for practice purposes. ## extract rows 5 through 7 and all variables
UNpop %>% slice(5:7)
grade_this_code()
slice()
and select()
functions to extract and print rows 5 through 7 of the world.pop
variable of the UNpop
data frame.## extract values 5 through 7 of the world.pop variable
UNpop %>% slice(5:7) %>% select(world.pop)
grade_this_code()
To select a particular variable that meets specific conditions, you can use the filter()
function.
filter()
function to extract the observations up to and including 1990.# use the filter() function to extract the observations
UNpop %>% filter(year <= 1990)
grade_this_code()
submission_ui
submission_server()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.