Practice 2: Scripts, Comments, Errors, Packages, and R Projects

Let’s work through what you saw in Week 2 together. Rather than treating this as a separate assignment, think of it as picking up where the lessons left off: we’ll walk through the same ideas step by step, and you’ll try each one out for yourself.

Due Sunday, 10/11 at 11pm.

Lesson Topic Video Slides What you’ll practice here
7 R scripts Video Slides R scripts, Step B
8 Comments Video Slides Comments, Step E
9 Common errors Video Slides Common errors, Step D
10 Introduction to the HRS dataset Video Slides The HRS dataset
11 Packages Video Slides Packages, Steps B and D
12 R projects and working directories Video Slides R Projects, Steps A and F
TipHow this works

There are two kinds of questions on this page:

  • Code boxes are little sandboxes you can type R code into. Click Run Code to run and check your answer. A green box means you’ve got it; an orange box means it’s not quite right yet and will nudge you toward the fix. Stuck? Click Show Hint (and Next Hint if there’s more than one). Want a clean slate? Click Start Over. Format tidies up your spacing.
  • Multiple choice questions give you feedback as soon as you pick an answer. For select all that apply, tick every option you think fits, then click Check my answer. Each one has a Hint box you can open.

Your answers are saved in this browser as you go, so you can come back later. A few tasks are things you do on your own computer (in RStudio or your file browser), and those are marked ungraded self-check.

Turning it in: fill in the AI Use Statement, then follow the steps in Your turn: download your answers as a .qmd, render it in RStudio, and submit both the .qmd and the .html on Brightspace.

R scripts

Recall from Lesson 7: an R script (.R) is a document that holds your code and comments. Unlike typing in the Console, you can save your work in a script and come back to it later.

To… Do this
Create a script File → New File → R Script (or the New File icon in the toolbar)
Run a line Put your cursor on it, then Ctrl + Enter (Windows) / Cmd + Enter (Mac), or click Run
Run several lines Highlight them, then Ctrl/Cmd + Enter or Run
Save a script File → Save, or the Save icon
  1. Why write code in an R script instead of typing it straight into the Console?

Look at the “What is an R script?” slide in Lesson 7. The analogy there is a very basic Word or Google document.

  1. Which of these will run a line of code from your R script? Select all that apply.

Check the “How to run code in an R script?” slide in Lesson 7 (or the table above). There’s a keyboard way and a button way.

You’ve also been working in Quarto documents (.qmd) since Lesson 6. Both are files RStudio can open, but they’re built for different jobs.

  1. What’s the main difference between an R script (.R) and a Quarto document (.qmd)?

Think back to Lesson 6: the three building blocks of a .qmd are a YAML header, text, and code chunks. Which of those does an R script have?

You’ll make and save your own R script in Step B.

Comments

Recall from Lesson 8: R ignores anything after a # on a line. That lets you write comments, notes that people read but R skips:

# This is a comment
## This is also a comment
########## This is a comment that can help me section off code ##########
This is not a comment # but this part is a comment

Think of comments as note-taking for your future self (and anyone else reading your code). You don’t need one on every line. The most useful comments explain the why, not just the what.

  1. Which of these lines gives an error when you run it?

R only ignores text that comes after a # on the same line. Which line has words that come before any #?

  1. A classmate wrote a note to themselves above their code, but now the box below gives an error. Fix it so R skips the note and prints the total number of flu cases. Don’t delete the note!
NoteHint

What one character tells R “ignore the rest of this line”?

  1. Here’s a line of code from a blood pressure study:

    (130 + 142 + 155) / 3

    Which comment above it would help future you the most?

Look at the “Better use of comments” slide in Lesson 8: use comments to explain the why of your code.

You’ll write your own comments in Step E.

Common errors

Lesson 9 reminded us that errors are R trying to help you. First, figure out what kind of message you got:

Type Meaning
Error Code stopped; something went wrong
Warning Code ran, but R is flagging something suspicious
Message Informational; not a problem

Then read it for clues: which function is mentioned, and keywords like not found or unexpected.

  1. You run log(-1). R prints NaN and then:

    Warning message:
    In log(-1) : NaNs produced

    What is R telling you?

The first words of what R printed are Warning message. Check the table above.

  1. Run the code below as it is, and read the error. Then fix it so R gives you the square root of 225.
NoteHint 1

The error says could not find function "Sqrt". Is that exactly how you spelled the square root function in Practice 1?

NoteHint 2

R is case-sensitive: Sqrt() and sqrt() are different things.

  1. This line is missing something, so R can’t finish reading it. (In RStudio’s Console, you’d see the prompt change from > to + while R waits for you.) Fix it so it runs.
NoteHint

Count them up: how many ( are there, and how many )? Every ( needs a matching ).

  1. You run 5 + "10" and get:

    Error in 5 + "10" : non-numeric argument to binary operator

    What is R telling you?

Look for the keywords in the error, like the “Interpreting error messages” slide in Lesson 9 suggests. “Non-numeric” means “not a number.” Which piece isn’t a number? (You saw something similar in Practice 1 with sqrt("144").)

  1. You run clean_names(iris) and get:

    Error in clean_names(iris) : could not find function "clean_names"

    You’ve checked, and clean_names is spelled correctly. What’s the most likely problem?

Look at the “Function not found, package not loaded” slide in Lesson 9.

  1. A classmate runs install.packages(janitor) and gets Error: object 'janitor' not found. What’s the fix?

The error says R is looking for an object called janitor. Look at the “Object not found” slide in Lesson 9, and how install.packages() was written in Lesson 11.

  1. Try running the code below: 0.1 + 0.2 == 0.3 gives FALSE, even though the math is right! That’s a silent logic error. Replace the blank with the function from Lesson 9 that checks whether two numbers are “close enough,” so R gives TRUE.
NoteHint 1

Look at the “Silent logic errors” slide in Lesson 9. The function’s name says it checks whether all of something is equal.

NoteHint 2

It’s all.equal(), with a dot in the middle.

  1. Not every mistake is loud! Which of these mistakes can give you a wrong answer without any error? Select all that apply.

Look at the “Wrong argument name” and “Silent logic errors” slides in Lesson 9. Which mistakes did R not complain about?

You’ll fix a real “function not found” error in your own file in Step D.

The HRS dataset

Lesson 10 introduced the dataset we’ll use all quarter: data from the Health and Retirement Study (HRS), a long-running study of about 20,000 people in America that measures many aspects of aging, including health, retirement, and economic status. Our version has 2,728 individuals and includes household information, demographics, health behaviors, physical and mental health, and economic information.

  1. Why are we using a synthetic version of the HRS data instead of the real data?

Look at the “We are using synthetic data” slide in Lesson 10.

You’ll use the HRS codebook all quarter to look up what each variable means. Open it for the next question.

  1. In the codebook, find the variable srh. What does it measure?

Open the HRS codebook and search the page for srh (Ctrl + F / Cmd + F). Read the Description and Levels columns.

Packages

Lesson 11 compared packages to apps on your phone: they add functions and data that aren’t built into R.

How often How
Install Once (unless updating) install.packages("janitor") (quotes!), or pacman::p_load(janitor)
Load Every time you use it library(janitor) (no quotes), or pacman::p_load(janitor)

pacman::p_load() is the preferred way: it installs a package if it isn’t installed yet, then loads it.

  1. How often do you need to install a package, and how often do you need to load it?

Look at the “From installing to loading” slide in Lesson 11, and think about the phone app analogy.

  1. Here’s the error from Question 11 again: clean_names() lives in the janitor package. Fill in the blank line so the code below runs and shows the cleaned-up column names of the built-in iris data. Use either way of loading from Lesson 11: library() or pacman::p_load().
NoteHint 1

Put the package’s name inside library() or pacman::p_load().

NoteHint 2

pacman::p_load(janitor) or library(janitor), with no quotes needed.

  1. In pacman::p_load(janitor), what does the :: do?

Look at the “Install and load packages” slide in Lesson 11. Lesson 9 also used janitor::clean_names(iris).

  1. Lesson 11 grouped the packages we’ll use into three categories. Which category does readxl belong to?

The clue is in the name: read + xl (Excel).

  1. Which of these packages are for summarizing/visualizing data? Select all that apply.

Look at the “Packages used in this class” slide in Lesson 11, which sorts them into loading/saving, summarizing/visualizing, and wrangling. You can also search a package’s name online to see what it does.

  1. A classmate put this at the top of their .qmd file:

    install.packages("tidyverse")
    library(tidyverse)

    What’s the problem?

How often do you need to install a package (Question 17)? How often does the code in a .qmd run?

You’ll load packages at the top of your own files in Steps B and D.

R Projects and working directories

Lesson 12 was all about reproducibility: setting up your work so the whole folder runs anywhere, for anyone (including future you).

  • The working directory is the folder R is currently “looking at.” getwd() shows it.
  • setwd() hard-codes a path that breaks on any other computer, or when you move the folder. Don’t use it.
  • An R Project (a .Rproj file in your course folder) sets the working directory for you, every time, on any computer.
  • The here() function (from the here package) builds paths from the project folder, whether you’re in the Console or rendering a .qmd.
  1. True or false: even after you’ve created an R Project for your course folder, you should still add setwd() to the top of every .qmd file, just to be safe.

Look at the “Wrap-up” slide in Lesson 12.

  1. Which of these open your work inside your R Project, so the working directory is set for you? Select all that apply.

Look at the “Opening and using an R Project” slide in Lesson 12, especially the warning at the bottom.

  1. Use here() to build the path to the HRS data file, hrs_data.rds, which lives in the data_lessons folder of your course folder. Separate the folder and file names with a comma (the platform-agnostic way).
NoteHint 1

Put each name in quotes, folder first, then the file: "folder", "file.ext".

NoteHint 2

here("data_lessons", "hrs_data.rds")

  1. here() can also take one string with a forward slash between the names. Fill in the blank with the slash version of the path on the left, so R says TRUE.
NoteHint 1

Use here() again, but with just one set of quotes, and a / between the folder and the file.

NoteHint 2

here("images/PUBH_R.png")

  1. Your .qmd lives in the practice/ folder of your project. When you run code in the Console, R works from the project folder; when you render, R works from practice/. Which function gives you the same starting point in both?

Look at “The here package” slide in Lesson 12.

AI Use Statement

NoteAI Use Statement

Using AI is not required in this class. If you did use an AI tool (ChatGPT, Claude, Copilot, Gemini, an RStudio assistant, etc.) on this practice, add a brief AI Use Statement. Include:

  • Which tool(s) you used
  • What for (a sentence or two, with question numbers)
  • Where it contributed to any written answers (if at all)
  • You do NOT need to link your conversation.

For example:

AI Use Statement: Claude was used to explain an error message in Question 7. All reasoning and answers are my own.

OR

AI Use Statement: AI was not used in this assignment.

Before using AI, check the table of allowed uses in the Generative AI Policy. For practice, AI can help you understand (explain an error or a concept, explain what a function does, check an answer you already worked out), but it should not do the problem for you. A half-finished answer that shows your thinking is always better than a polished one from AI!

Fill in your statement below. It’s saved as you type, and it goes at the top of your downloaded .qmd, right where your submission needs it.

Your turn: working in a real project

Now let’s put this week together in RStudio. These steps are ungraded self-check, but your downloaded .qmd (and the .html you render from it) is what you turn in.

Step A. Make your course folder an R Project (Lesson 12). In RStudio, go to File → New Project → Existing Directory, browse to your PUBH_523_26F folder, and click Create Project. You should now see PUBH_523_26F.Rproj in that folder. From now on, open your work by double-clicking that .Rproj file (or picking the project in RStudio’s top-right corner). To check, look at RStudio’s top-right corner: it should say PUBH_523_26F, not Project: (None).

While you’re here: run pacman::p_load(here) in the Console. If R says there is no package called 'pacman', run install.packages("pacman") in the Console once (not in a file! See Question 22), then try again.

Step B. Write and save an R script (Lessons 7 and 11). With your project open, go to File → New File → R Script. Type the lines below (the same packages as the “Install and load packages” slide in Lesson 11), then run them with Ctrl + Enter / Cmd + Enter:

# Load packages ----
pacman::p_load(
  tidyverse,  # most of what we need
  here,       # loading/saving data
  readxl,
  haven,
  writexl,
  janitor,    # summarizing/visualizing data
  rstatix,
  gt,
  gtsummary,
  naniar
)

# Where is my project folder?
here()

The first time, p_load() installs any packages you don’t have yet, so it may take a few minutes. That’s normal! After that, it just loads them. This gets you set up for the rest of the quarter.

Save the script in your practice/ folder as 02_packages_and_paths.R (lowercase, underscores, and a leading number, just like Lesson 5). You don’t need to turn this script in.

Step C. Download your answers and open them. Click Download my answers as .qmd at the bottom of this page. Move the file into PUBH_523_26F/practice/, and rename it lastname_firstinitial_practice_02.qmd. In RStudio (with your project open), open it from the Files pane. Change author: in the YAML to your name.

Step D. Your first render fails on purpose (Lessons 9 and 11). Click Render. It will stop with an error that says could not find function "here". That’s Lesson 9’s “function not found, package not loaded” error! Even if you loaded here in the Console, rendering starts a fresh R session that only knows what’s written in the file. To fix it, find the Load packages chunk at the top of your file and add:

pacman::p_load(here, janitor)

Then render again. It should work this time.

Step E. Comment your code (Lesson 8). In your .qmd, scroll to the Comments (Lesson 8) section and find the chunk labeled Step E. It has one line of code and no comments:

(520 + 310 + 480 + 275) / 50000 * 10000

Where to type: inside that code chunk, on new lines above the line of code. Start each comment line with #, and don’t change the code line itself. Add two comments:

  • a section-off comment, like ########## Chlamydia case rate ##########
  • a comment saying what the line calculates and why the health department cares (use the background below)

When you’re done, your chunk should have this shape:

########## Chlamydia case rate ##########
# Your comment: what this calculates, and why it matters
(520 + 310 + 480 + 275) / 50000 * 10000

Background: Multnomah County’s health department tracks chlamydia (the most commonly reported STI in the county) by neighborhood, so it knows where to send testing and outreach. The four numbers are 2023 chlamydia case counts from four Northeast Portland zip codes (97211, 97212, 97213, and 97218). The 50,000 is the combined population of those zip codes. Multiplying by 10,000 turns it into a rate per 10,000 residents, which makes areas of different sizes easy to compare.

Render to make sure you didn’t break anything. Your comments will show up in the code in your .html, but R skips them, so the result is the same.

Step F. Compare getwd() and here() (Lesson 12). In your .qmd, scroll to the R Projects and working directories (Lesson 12) section and find the chunk labeled Step F. Run both lines of the chunk in the Console (Ctrl + Enter / Cmd + Enter), then render and look at the same chunk in the .html. Below the chunk (as regular text, not inside it), write 1–2 sentences: Which output changed between the Console and the render, and which stayed the same? Why does that make here() the safer choice for file paths?

Step G. Render and submit. Render one last time. Check that your AI Use Statement shows at the top of the .html. Then submit both your .qmd and .html on Brightspace.


Didn’t finish every question? That’s okay! Practice is graded on completion: you get credit for answering at least 75% of the question parts, whether your answers are right or wrong. Anything you haven’t finished shows up as Not answered yet or Not finished yet in your download, and won’t stop your file from rendering.

Check your overall progress on this practice set on the My Progress page.