Block 6: Break it on purpose

Week 2 · Introduction to R · debugging · about 8 min

NoteHow this works

Read the code and predict (write it down or tell your neighbour), answer the question, then run it with Run Code. Every cell is editable; Start Over resets it. Errors are information: read them.

Each cell below contains one error. Run it, read the message, and fix it.

Symptom Common cause
could not find function "xyz" Typo, or package not loaded (library())
object 'xyz' not found Typo, case mismatch, or the creating line was not run
cannot open file ... Wrong working directory or file name
unexpected symbol / unexpected ')' Missing comma or unbalanced parentheses
Result is NA Missing values: consider na.rm = TRUE

1. What does the error say?

Read this code (it is not run yet):

mean(world.popp)
Predict: What kind of error message will mean(world.popp) give?
The object name has a typo, so R cannot find it.

Now run it and compare with your answer:

# Compare the name with the object you created.
mean(world.pop)
mean(world.pop)

2. And this one?

Read this code (it is not run yet):

Mean(world.pop)
Predict: What kind of error message will Mean(world.pop) give?
R is case sensitive: Mean is not mean, and it is used as a function.

Now run it and compare with your answer:

# R is case sensitive.
mean(world.pop)
mean(world.pop)

3. And this one?

# Check the file name: capital letters matter on Linux and Mac.
UNpop <- read.csv("UNpop.csv")
UNpop <- read.csv("UNpop.csv")

4. And this one?

# Count the opening and closing parentheses.
sum(c(1, 2, 3))
sum(c(1, 2, 3))

5. And this one?

# Typo in the package name. Packages: install.packages() once per computer, library() in every session.
library(foreign)
library(foreign)
TipHabits that save you

Scripts are the product: raw data + script should recreate everything from a fresh R session. Comment the why, change one thing at a time, and ask: does this number make sense?