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.
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.
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
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:
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!
Try these on your own:
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.
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.