Lab 02 Basics of R and RStudio

URBAN 520 Quantitative Methods in Urban Design and Planning

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

You can change the layout and theme in Tools > Global Options > Pane Layout/Appearance.

RStudio window with panels

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:

  1. Choose File > New File > R Markdown…
  2. Select HTML and click OK (select PDF if you’d like PDF as outputs)
  3. Save the file somewhere, call it any_name.Rmd
  4. Click the Knit button
  5. Watch the progress in the R Markdown pane, then gaze upon your result!
Create a New R Markdown

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 interface in RStudio

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.

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:

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 → FALSE

Functions 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 arguments

The 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 vector

After 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?

# TODO

In 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.

# TODO

Let’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?

# TODO

Create a vector with those two dates.

# TODO

Let’s use indexing [] to select today’s date, then subtract your birthday. What’s happened?

# TODO

Can 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).

# TODO

Then, 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}.