Lab 02 Basics of R and RStudio
URBAN 520 Quantitative Methods in Urban Design and Planning
- Getting Started
- R Markdown
- R Code in R Markdown
- Math and Logical Operation in R
- Functions and Help
- Common Data Types in R
- Data Structures in R
- 📚 TODO: R Basic Review Tasks
Getting Started
Open up RStudio now and try to download the Lab 02 source file, a
rmd (R Markdown) file from the course website, and open it
on your local machine.
Use install.packages("[package name]") to install any
required packages, or RStudio may automatically recognize that there are
some packages you need to install and will install them for you.
# For example, this code below will install cleanrmd (for the beautiful theme)
# install.packages("cleanrmd")RStudio Interface
- Top Left: Code editor pane and data viewer
(browse with tabs). Here you can type text, R commands, and run R
commands. Leave the cursor anywhere on the line where the command is and
press
Ctrl+Enter(Cmd+Returnfor Mac) or click on theRunicon above. Output will appear in the console below. - Bottom Left: Console for running code
(
>prompt) - Top Right: The environment tab shows all the active objects. The history tab shows a list of commands used in the session.
- Bottom Right: The files tab shows all the files and folders in your default workspace as if you were on a PC/Mac window. The plots tab will show all your graphs. The packages tab lists the packages available and can install packages.
You can change the layout and theme in Tools > Global Options > Pane Layout/Appearance.
R Markdown
Markdown is a simple formatting syntax. For more details on using R Markdown see http://rmarkdown.rstudio.com. In the lab, we will review some basic Markdown syntax using Markdown Live Preview.
You can put some math \(y= \left(\frac{2}{3} \right)^2\) right up in there using \(\LaTeX\). \[\frac{1}{n} \sum_{i=1}^{n} x_i = \bar{x}_n\] Note: \(\LaTeX\) is not required in this class. If you are curious about how mathematicians compile their books, you may refer to the Learn LaTeX in 30 minutes from Overleaf. Overleaf is the most popular collaborative cloud-based \(\LaTeX\) editor and UW students can get Overleaf Premium account for free.
R Markdown Documents
This document is an R Markdown file, you can create a new one by:
- Choose File > New File > R Markdown…
- Select HTML and click OK (select PDF if you’d like PDF as outputs)
- Save the file somewhere, call it
any_name.Rmd - Click the Knit button
- Watch the progress in the R Markdown pane, then gaze upon your result!
You may also open up the HTML file in your computer’s browser if you so desire, using the Open in Browser button at the top of the preview window.
You can also work on the R Markdown file using Visual
mode (above this editor window), which will show the rendered file.
R Markdown Interface
R Markdown Headers
The header of an .Rmd file is a YAML code block, and everything else is part of the main document. To mess with global formatting, you can modify the header.
---
title: "Untitled"
author: "Name of a person"
date: "October 1, 2026"
output:
html_document:
toc: true # including a table of contents
theme: readable # using a theme called readable
---
R Markdown Tinkering
R Markdown docs can be modified in many ways. Visit these links for more information.
- Ways to modify the overall document appearance
- Ways to format parts of your document
- R Markdown: The Definitive Guide
R Code in R Markdown
Inside R Markdown, lines of R code are called
chunks. Code is sandwiched between sets of three
backticks and {r}. This chunk of code…
```{r}
mean(c(1,2,3,4,5,6))
```
Produces this output in your document:
mean(c(1,2,3,4,5,6)) # calculate the mean value of a list of numbers## [1] 3.5
Chunk Options
Chunks have options that control what happens with their code, such as:
echo=FALSE: Keeps R code from being shown in the documenteval=FALSE: Shows R code in the document without running itinclude=FALSE: Hides all output but still runs code (good forsetupchunks where you load packages!)results='hide': Hides R’s (non-plot) output from the documentcache=TRUE: Saves results of running that chunk so if it takes a while, you won’t have to re-run it each time you re-knit the documentfig.height=5, fig.width=5: modify the dimensions of any plots that are generated in the chunk (units are in inches)
Some of these can be modified using the gear-shaped Modify Chunk Options button in each chunk. There are a lot of other options, however.
Editing and Running Code
In R Markdown documents, click within a code chunk and click the
green arrow to run the chunk. The button beside that runs all prior
chunks. The console will show the lines you ran followed by any
printed output. There are more options on the top right of this window
(green arrow with Run).
pi # output the value of pi## [1] 3.141593
Sometimes we want to insert a value directly into our text. We do
that using code in single backticks starting off with r.
For example, the value of pi rounded to the nearest three
decimals is 3.142.
Math and Logical Operation in R
# Math operations
2 + 3 # addition → 5
5 - 2 # subtraction → 3
4 * 6 # multiplication → 24
10 / 4 # division → 2.5
2^3 # exponentiation → 8
10 %% 3 # modulo (remainder) → 1
sqrt(400) # square root of 400 → 20
x <- c(2, 4, 6, 8, 10) # Create those numbers to calculate
mean(x) # average → 6
var(x) # sample variance (divides by n - 1)
sd(x) # sample standard deviation (divides by n - 1)
sum(x) # sum of all elements
min(x) # smallest value
max(x) # largest value
range(x) # min and max together
length(x) # number of elements# Logical operations
3 == 3 # equal → TRUE
3 != 4 # not equal → TRUE
5 > 2 # greater than → TRUE
2 < 1 # less than → FALSE
5 >= 5 # greater or equal → TRUE
2 <= 3 # less or equal → TRUE
TRUE & FALSE # AND → FALSE
TRUE | FALSE # OR → TRUE
!TRUE # NOT → FALSEFunctions and Help
sqrt() is an example of a function in
R. If we didn’t have a good guess as to what sqrt() will
do, we can type ?sqrt in the console and look at the
Help panel on the right.
?sqrt # what is sqrt()? Arguments are the inputs to a function. In
this case, the only argument to sqrt() is x
which can be a number or a vector of numbers. Help files
provide documentation on how to use functions and what functions
produce.
Common Data Types in R
R has several basic data types that are used to build larger data structures.
| Data Type | Example | Description | Check with |
|---|---|---|---|
| Numeric | x <- 3.142 |
Decimal numbers (floating point) | is.numeric(x) |
| Integer | y <- 5L |
Whole numbers (the L forces integer type) | is.integer(y) |
| Character | z <- "Hello" |
Text or string values | is.character(z) |
| Logical | flag <- TRUE |
Boolean values: TRUE or FALSE | is.logical(flag) |
| Factor | f <- factor(c("A", "B", "C")) |
Categorical values with fixed levels | is.factor(f) |
You can also check type with class() or
is.*() functions.
Data Structures in R
Objects
R stores everything as an object, including data,
functions, models, and output. Creating an object can be done using the
assignment operator: <-:
new_object_preferred <- 144
new_object_not_preferred = 144
# using `=` is OK in R but not recommended; `=` is mainly for function argumentsThe Environment Pane (right top) shows all active objects
once you create them in your current R session. Each assignment
(<-) updates this list. Then, you can display or ‘use’
an object simply by using its name.
new_object_preferred## [1] 144
sqrt(new_object_preferred)## [1] 12
Object names can contain _ (preferred) and
. in them but CANNOT begin with numbers. Try to be
consistent and clear in naming objects. Clear naming will help you save
lots of time in the future!
Vectors
Vector is a sequence of elements of the same type.
numbers <- c(1, 2, 3, 4) # numeric vector; `c()` means combine
people <- c("Alice", "Bob") # character vectorAfter creating them, we often want to inspect what they contain and their structure.
print(numbers) # show the values## [1] 1 2 3 4
length(numbers) # check the number of elements## [1] 4
class(numbers) # check the type## [1] "numeric"
numbers > 2 # check whether each element is larger than 2## [1] FALSE FALSE TRUE TRUE
We may also want to select some elements in one vector.
numbers[1] # show the first element## [1] 1
numbers[-1] # show the vector without the first element## [1] 2 3 4
numbers[1:3] # show the elements with index 1 to 3## [1] 1 2 3
numbers[c(1,3)] # show the elements with index 1 and 3## [1] 1 3
numbers[c(TRUE, TRUE, FALSE)] # show the elements with `TRUE`## [1] 1 2 4
Matrix
A 2D collection of elements of the same type (optional for this class).
mat <- matrix(1:6, nrow = 2, ncol = 3)
dim(mat) # dimensions (# of rows, # of columns)## [1] 2 3
Lists
A collection of objects (can be of different types). List members can
be named, referenced using the [[ operator or using the
names. Note: list[ ] will keep the result as a
list (still wrapped).
my_list <- list(name = "Alice", age = 25, scores = c(90, 85, 88))my_list$age # get element by name ("age" = 25)## [1] 25
my_list[[2]] # get element by position (2nd element = 25)## [1] 25
my_list[2] # still a list with "age = 25"## $age
## [1] 25
Dataframe
Most data sets you will work with will be read into R and stored as a dataframe, so this course will mainly focus on manipulating and visualizing these objects. We will leave dataframe to next lab session.
📚 TODO: R Basic Review Tasks
What’s your birthday (or any special day for you)? Please print
it out using the format YYYY-MM-DD without showing the R
code in the output HTML document. What’s the data type of your
YYYY-MM-DD object?
# TODOIn R, a date can be defined as a class called Date
using the function as.Date(). Look up the documentation of
this function and tell me what’s the simplest argument this function
needs. Then, assign your birthday to an object.
# TODOLet’s find the date for today! We need to use a function called
Sys.Date() to always get “today”. Check the documentation,
what argument do we need?
# TODOCreate a vector with those two dates.
# TODOLet’s use indexing [] to select today’s date, then
subtract your birthday. What’s happened?
# TODOCan you calculate your age by simply dividing the difference in
days by 365? Note: The calculation doesn’t account for the
exact month/day alignment — it just assumes each year is a flat 365
days. You can install package lubridate to calculate a more
precise age (optional).
# TODOThen, finish the sentence using inline R code:
Today is today's date, it has been
number of year years since {what did happen on the big day,
such as my birthday}.