library(learnr) library(bst290) knitr::opts_chunk$set(echo = FALSE)
As before: De-bugging is unfortunately a part of working with computer code. In the following exercises, you get a piece of code that does not work and have to figure out how to fix it.
In all exercises, you will work with the small ess
dataset that you used in the main tutorial and which you should therefore be familiar with (otherwise, quickly go over the main tutorial again to refresh your memory).
Here you want to calculate the average age of your respondents --- but R
refuses...
average(ess$agea)
Obviously, the problem was that the function to calculate an average in R
is called mean()
, and not average()
. You may find that strange or stupid, but it just is that way...
Here is how you make that code work:
mean(ess$agea)
You want to see the first 20 observations of the ess
dataset -- but R
only shows you the first six. How can you get 20?
head(ess)
This one is solved by setting the number of rows to 20 with the n
option:
head(ess, n = 20)
You want to calculate the standard deviation of the agea
variable, and you definitely have the correct function and variable --- but something still causes an error:
sd(ess@agea)
The issue was that the wrong symbol was used to indicate that R
should use a specific variable from the ess
dataset: This is done with the $
symbol, not with @
:
sd(ess$agea)
quiz(caption = "Final (brief) quiz", question("What is the correct function to get a list of the distinct categories of a variable?", answer("`unique()`", correct = T), answer("`distinct()`", message = "Not quite - try again!"), answer("`categories()`", message = "Unfortunately not - but don't give up, you know this!"), random_answer_order = T, allow_retry = T), question("How does `R` like to store categorical variables?", answer("As *factors*", correct = T), answer("As *categoricals*", message = "Not quite - try again!"), answer("As *levels*", message = "Unfortunately not - but don't give up, you know this!"), random_answer_order = T, allow_retry = T), question("How can you get the last few observations of a dataset?", answer("`tail()`", correct = T), answer("`end()`", message = "Not quite - try again!"), answer("`last()`", message = "Almost...keep trying."), random_answer_order = T, allow_retry = T))
Congrats, you are done! Now you know how you can get summary statistics and familiarize yourself with a new dataset.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.