Outline

Running cells

In an R Markdown notebook, you work with two main components:

  • Markdown cells — used for text, explanations, and formatting.

  • Code chunks — used for writing and running R code. You can create a new code chunk by clicking Insert → R in the toolbar or by using the shortcut Ctrl + Alt + I (Windows) or Command + Option + I (Mac).

To run a code chunk, press Command + Return (Mac), or Ctrl + Enter (Windows), or click the ▶️ Run button. Running a chunk executes all of the code it contains.

Variables

A variable is simply a name that stores a piece of information—like labeling a box so you remember what’s inside.

In R:

  • Variable names can include letters, numbers, and underscores.

  • They cannot begin with a number.

  • They are case-sensitive (age and Age are different!).

  • To create a variable, use the assignment operator <-:

Example:

my_age <- 25

After you make a variable, you can use it anywhere in your code— print it, do math with it, save results, and more.

Data types

Every value in R has a data type, which determines how the computer stores it and what operations you can perform. Common types include numbers, text, and logical (true/false) values.

Here are a few basic types you will encounter:

Type Description Example
num Numbers 10, -3, 42
chr Text strings “Hello”, “R”
logi True/False values TRUE, FALSE

Examples:

str(10)
##  num 10
str('Julia')
##  chr "Julia"
str(TRUE)
##  logi TRUE

Comments

Comments let you add notes or explanations to your code. They’re meant for humans, not the computer! In R, a comment starts with a # symbol. Everything after the # on that line is ignored by R when the code runs. This makes comments a great way to explain what your code is doing or to leave reminders for yourself.

# This is a comment. It is not evaluated when we run our code

Knitting your R Markdown File

Once you’ve written your R Markdown file, you can turn it into a polished HTML or PDF document. This process is called knitting.

Knitting runs all of your code chunks in order and combines the results with your text to create a final report.

To knit your file:

  • Click the Knit button at the top of the RStudio window.
  • Choose your preferred output format (e.g., HTML, PDF).
  • RStudio will render the document and open the finished file automatically.

Note: To knit to PDF, you need a LaTeX installation (e.g., TinyTeX). If this isn’t installed, knitting to PDF may give you an error. For simplicity, let’s stick to knitting an HTML file!

Knitting is a great way to share your results, produce assignments, or create reproducible reports!

Your turn!

Try these on your own:

  1. Create three variables: your_name, your_age, and your_favorite_number.
  2. Run the chunks to see your results!
your_name <- "Hoang"
your_age <- 19
your_favorite_number <- 30

When you’re finished, knit this Rmd file to HTML and upload the knitted HTML file to Quercus for this week’s participation mark.