There are a few types of assignments in this course that require the use of R/RStudio for carrying out analytic tasks: Labs, Application Challenges, and the Final Project. A few things to know for now:
For all assignments listed above, you will be working with R code. Think of R code as a set of written instructions that tells the statistical software R exactly what to do with your data. Instead of clicking through menus, you will type commands that allow you to clean data, run analyses, and create tables and figures to share your results. One major benefit of working with R code is that your analytic process is clearly documented and can be easily reproduced (by future you, your colleagues, and/or readers of your work).
Much of the code you will use is provided in the Lab Guides, which are designed to walk you through each step of the analytic process.
I want to emphasize that this is not a coding course. The primary goals of this class are to help you understand and select appropriate analytic methods and to accurately interpret and communicate results from public health research. That said, by working with R throughout the semester, you will also leave this course with practical, concrete skills that are widely used in public health research.
As you begin working in RStudio, you’ll encounter different file types for writing and running R code. Two of the most common are:
.R):.Rmd):.Rmd files
ideal for sharing your work in a professional and reproducible way.
In this course, we will use R Markdown files for all assignments.
If you are using your personal computer for this course, it’s best to set up a clean and efficient file management structure. File management is key to preventing R programming frustration. Here are some tips:

As discussed on the Home page, R is a programming language designed for statistical computing and graphics, while RStudio provides a user-friendly interface for working with R. You need to have both programs installed; however, we will only use the RStudio application to complete assignments in this course. You will not actually need to open the R application at any time.
When you open RStudio, you’ll see the interface is divided into four main windows (see image below):
The RStudio Interface
.R or .Rmd file, it
is the content in your Editor window that is being saved for later
use.As we will be using R Markdown documents (with a .Rmd
extension) for all assignments, it is important for you to have a basic
understanding of these files before we begin working with RStudio. This
section provides a brief introduction to R Markdown, including how to
create and save an R Markdown document within RStudio, the major
components of an R Markdown document (YAML header, R code chunks, and
text - each discussed below), and how to “knit” an R Markdown document
(in other words, how to go from an R Markdown document to a nicely
formatted report).
Once again, we will use R Markdown files for all assignments. To
create a new .Rmd file in RStudio, select File → New File →
R Markdown. A window should pop up. Type in the name of the assignment
you are working on (e.g., Lab 1) next to Title and your name next to
Author. Leave everything else alone and click OK. A new window in the
top left of your RStudio console should pop up containing your new R
Markdown file (see example below).

You will notice that your new R Markdown file already has some
“stuff” in it. R Markdown essentially provides some basic instructions
for using an R Markdown file, but we don’t necessarily need to include
that in our assignments. Before you get started on the
assignment, you can go ahead and delete everything below the “r setup”
chunk. (“Chunks” are the sections you’ll see shaded in light
gray; more info below). In other words, leave the chunk that starts with
“{r setup, include = FALSE}” and delete everything below it. Then, you
will actually have a clean .Rmd file to work from.
Using the basic organizational guidelines above, save your R Markdown file into an appropriate folder by clicking on File and then Save from the RStudio menu.
To open a .Rmd file in RStudio, select File → Open File
and navigate to the folder where you saved the assignment template and
select the file. You should see the R Markdown file pop up on the top
left portion of your RStudio interface (Editor window).
R Markdown documents contain 3 major components:
The YAML header controls how R Markdown renders your
.Rmd file. The YAML header is surrounded by - - - marks and
is always located at the top of your Rmd file.
In the assignment’s YAML, add your name, assignment number, and the date. These are the only necessary items, but you can change other options, most of which are detailed here. Your YAML will generally look like the following:
---
title: "Assignment X"
subtitle: PUBH 207B
author: Your full name here
date: Assignment due date
output: html_document
---
When answering an assignment question, you’ll generally have the following sequence of components in your R Markdown document: question identifier (e.g., section name and number), R code used for answering the question, comments describing what the code is doing (i.e., annotations), and text to explain the results (i.e., your interpretation). For example, let’s say you have the following question in one of your assignments:
Question 1
1+1
1. What is the result of the operation above?
Assignments will ask you to write R code to accomplish analytic
tasks. You will present and execute your R code inside R code chunks
(yes, they are really called “chunks”). R code chunks start with
```{r} and end with ```, and you insert your R
code in between. You can also easily create a new code chunk by clicking
on
located at the top of the R
Markdown window and select R (the first option in the list).
Using the example question above, to carry out the operation
1+1 as R code, it will look like the following in your R
Markdown document:
All code inside a chunk will be executed when knitting the R Markdown file (more on knitting soon). This means that your R code must reside inside an R code chunk in order for it to be processed as R code. R will interpret anything outside of R code chunks (i.e., in the unshaded areas of your R Markdown document) as plain text.
On Application Challenge assignments and Final Project, you are
expected to annotate your R code so that I (as well as future you and
your collaborators) know what is being done in that line of code. You
designate annotations or comments in R code using the #
symbol. In programming, comments are bits of text that are not
interpreted as computer instructions — they aren’t code, they’re just
notes about the code. Since computer code can be opaque and difficult to
understand, comments help explain the meaning and purpose of our code.
While a computer is able to understand the code, comments are there to
help people understand it. This is particularly important when someone
else will be looking at your work — whether that person is a
collaborator, or is simply a future version of you (e.g., when you need
to come back and fix something and so need to remember what you were
thinking when you first wrote the code).
Comments should be clear, concise, and helpful — they should provide
information that is not otherwise present or “obvious” in the code
itself. So, to annotate the above line of code 1+1, you
could add in your R code chunk:
Annotations like this should be inside each code chunk, after a
#. When the # symbol is in front of text within a
code chunk, R knows that what follows is not code but rather is plain
text being used to explain the code.
The first line of an R code chunk has {r}. Next to the r, we can give the chunk a name, such as:
Here, I named the chunk “q1chunk1” which indicates this is question 1, chunk 1. You can name the chunk whatever you like. The chunk name is not required; however, it is good practice to give each chunk a unique name (we’ll see its value later when we talk about knitting).
In the R Markdown document you created and saved, you will notice the following R code chunk has automatically been included after the YAML header:
The above code establishes global options for every R code chunk in your R Markdown file. These options alter the way R results are spit out in your final formatted document. I suggest adding the following global options in every R Markdown assignment file:
The above code hides non-error messages for every single R code chunk in your file. These non-error messages are unnecessary for the purposes of this class. Other chunk options can be found here.
You can also set options for individual chunks. These are local
options - meaning local to that chunk - and won’t be applied to other
chunks in your file. For example, you can add the options
warning=TRUE and message=TRUE to an individual
R code chunk as follows if you want to show the messages for the R code
in that particular chunk. Notice that each argument is separated by a
comma:
In addition to writing R code to carry out analytic steps, you will be expected to provide an interpretation of your results. Going back to our example question from above:
Question 1
1+1
1. What is the result of the operation above?
You would type in your R Markdown document something like:
The question identifier and your written interpretation of the results should be placed outside of the R code chunk, as regular text in your R Markdown file.
When you knit your R Markdown file (more on knitting shortly), R runs all of the code inside each code chunk and then combines the code, output (i.e., result), and text into a single, polished report. The output from each code chunk will appear automatically in the knitted document, even if you do not see it directly below the code while you are working (though you should see the output in the Console when running each chunk). For this reason, you should write your interpretation directly below each code chunk in plain text. When you knit the document, the code output will appear first, followed by the output and your written interpretation in the final report.
Please do not put all of your code for an entire assignment or even a single question in one single chunk. For example, let’s say you see the following question in an assignment:
Question 1
(a) 1+1
(b) 2+2
Run each line of code above. What are the results?
Instead of including both lines of code in one chunk like as follows…
Question 1
```{r}
# this code adds one plus one
1 + 1
# this code adds two plus two
2 + 2
```
One plus one equals 2. Two plus two equals 4.…break it up and add text after each to explain the result:
You may have multiple code chunks for a single item. It just depends on how complex the question is - there may be multiple steps involved. Use your best judgement to determine the most appropriate way to break up your code, keeping in mind that there are always many different ways to accomplish the same task in R.
After you write code in a chunk, you’ll need to test the code to make sure it is running properly. In other words, rather than writing all the code and then running it at the end of the assignment, run the chunks one at a time. To elaborate, let’s say the first question in an assignment asks you to add one plus one. In your R Markdown document, type in the following to answer this question:
Run that code chunk to make sure it works (you should get 2!). Then proceed to the next question. Let me emphasize: Do not write all of your code answering every question in the assignment and run it at the very end. Routinely TEST, Test, and test your code to make sure it runs properly.
There are a number of ways to run code in R Markdown. First, you can
click your mouse in the R code chunk you want to run and click on
located at the top of the R
Markdown window and select Run Current Chunk.
Second, you can place your mouse cursor in the R code chunk and click
on
located on the right corner
of the chunk. See Figure below.

In each R code chunk, pressing the button
will run all
previous R chunks. See Figure below.

Knitting puts an assignment’s main components - code,
output, and text - in a nicely formatted document. You can create three
types of knitted documents: html, Microsoft Word, or PDF. For all
assignments in this course I would like you to knit to an
html file because it is the easiest of the three
options.
To Knit your document, click
, which will be located at the
top of the upper left R Markdown window.

When you start knitting, you will notice that a new window on the bottom left will appear in place of the Console. The window will show the progress of your knitting. When you knit, R is going through each R code chunk one at a time, starting from the top and moving down. The percentages you will see are based on the proportion of your R Markdown file that R has successfully knitted. See Figure below.

If there is a problem knitting, R will stop at the chunk that
contains the problem. You can determine the offending place in your R
Markdown file two ways. First, in the R Markdown tab in the bottom left
window, if you click on “Output” located at the top right corner of this
window, you will see the R Markdown progress window, the error in red,
and where R Markdown stopped. Carefully read the description of the
error, which will contain the R code chunk name and sometimes the lines
containing the problem in your R Markdown file. While not required, this
is where naming your code chunks can come in handy. You can go to your
offending chunk and see what may be the problem. For example, the figure
below shows knitting was stopped because the object xyz was
not created in the R Markdown file. You can go to the chunk named
“q2chunk2” to remedy the issue.

The other way to find where R Markdown is having trouble is by clicking on “Issues” also located at the top right corner of the R Markdown window. The error will give you something similar to what you found in the Output window, but instead of a chunk, it will tell you the specific line in your R Markdown file that this error is located. Go to that line in your R Markdown file and see what is the issue. For example, the error here is located in line 34.

If everything goes smoothly and you encounter no errors, a preview of
your knitted document will pop up in a new window and the
.html file will automatically be saved in the folder where
your R Markdown file resides.
I recommend not waiting until the very end of an assignment to knit. When you finish one question, knit your document to see if everything is working properly. If it is working for that question, move on to the next question. You can knit over and over again, and each time the knitted file in your folder will be replaced by the newest version. So, don’t be afraid to knit just because you aren’t finished with an assignment yet.
There are two things you’ll have to deal with: (1) making sure the R code is working correctly to get the results you need in order to answer the question; and (2) making sure the code is working correctly to knit a final document. These two issues may be related (for example, if your R code is producing an error, R Markdown will not knit), but sometimes they are not. So, check both your R code and your knitting results often. And absolutely do not wait until the last minute to knit. Knit as often as possible.
When you’re satisfied with the end product, submit your R Markdown
document (with an .Rmd extension) and final knitted
.html document to the corresponding assignment page on
Canvas. Note that both files are required for your assignment
to be graded.
Use the following workflow for all assignments in this course:
1. Review the week’s materials first.
Make sure
you understand the concepts before starting the assignment.
Skipping this step is the most common reason students
struggle. You need a solid grasp of the content to understand
what each assignment question is asking.
2. Set up your assignment folder.
Create a
folder on your computer to store assignment files. You may use one
folder for all assignments or separate folders for each — what matters
is that your files are organized and easy to locate.
3. Create your R Markdown file.
Create a new R
Markdown document following the instructions provided earlier on this
page. Save it in the appropriate assignment folder. Remove the default
text and code chunks that appear below the {r setup} chunk.
4. Download and save the data.
Download the
required data file(s) from Canvas and save them in the same folder as
your .Rmd file.
5. Work through the assignment questions in
order.
For each question, use the following structure:
As you work:
6. Knit early and often.
After completing the
first question, knit your document to an .html file and confirm that it
knits without errors. Fix any issues before moving on to the next
question.
7. Repeat for all questions.
Continue working
through each question, knitting periodically to ensure your document
continues to knit successfully.
8. Submit your files on Canvas.
Once all
questions are complete and the document knits successfully, submit both
required files by the deadline.
For each assignment, upload two separate files to Canvas:
Please do not combine these files into a zipped folder. They should be uploaded as two separate documents.
If this page feels overwhelming right now, that’s okay. Much of this will make more sense once you begin working with R/RStudio, and you can return to this page as a reference throughout the semester. Remember that you are not expected to know everything at the start, and I am here to support you at every step. If you have questions at any time, please don’t hesitate to reach out.
Jenny Wagner, PhD, MPH
Assistant Professor
Department of Public Health
California State
University, Sacramento
jenny.wagner@csus.edu