Lab 1
Lab 1
Keri Hu
1/26
Today’s objective
2/26
RStudio interface
3/26
Arithmetic operations
5 + 3
## [1] 8
5 / 3
## [1] 1.666667
5 ^ 3
## [1] 125
5/26
Create objects
R can store objects with a name of our choice. Use <- as an assignment
operator for objects.
object_1 <- 5 + 3
object_1
## [1] 8
If we assign a new value to the same object name, then we will overwrite
this object (so be careful when doing so!)
object_1 <- 5 - 3
object_1
## [1] 2
6/26
Objects (cont.)
## [1] "HKU"
7/26
A vector stores information in a given order
We use the function c(), which stands for “concatenate,” to enter a data
vector (with commas separating elements of the vector):
## [1] 93 92 83 99 96 97
8/26
seq function
seq(0, 20, 5)
## [1] 0 5 10 15 20
• If you have 1000 data points, and you want to rank them from 1 to
1000, you can use seq(1, 1000, 1).
9/26
Retrieve part of a vector
vector.1[2]
## [1] 92
vector.1[c(2, 4)]
## [1] 92 99
vector.1[-4]
## [1] 93 92 83 96 97
10/26
Multiply a vector by a number
vector.1 * 1000
11/26
Element-wise operations of vectors
## [1] 4 5 6
vec1 * vec2
## [1] 3 6 9
vec1 / vec2
12/26
Functions
13/26
Functions (cont.)
length(vector.1)
## [1] 6
min(vector.1)
## [1] 83
max(vector.1)
## [1] 99
range(vector.1)
## [1] 83 99
14/26
Functions (cont.)
mean(vector.1)
## [1] 93.33333
sd(vector.1)
## [1] 5.680376
sum(vector.1)
## [1] 560
15/26
R script
• Reproducibility
• Anyone anywhere with data and R script can produce the results.
• Big time savings when repeating analysis on data
16/26
Create an R script
17/26
Specify a working directory in R
Working directory: the default location where R searches for files and
where it saves files
setwd("/Users/Keri/MACC7006")
getwd()
## [1] "/Users/Keri/MACC7006"
18/26
Loading data from working directory
Dataset WHO.csv: recent statistics about 194 countries from the World
Health Organization (WHO)
19/26
Data frames
Load WHO.csv, assign it to an object called WHO (as we did in the last
page), and try the above functions on this newly created data frame.
20/26
Example of a data frame
Variable 1 Variable 2
Observation 1 Variable 1’s value of Observation 1
Observation 2
Observation 3
21/26
Retrieve part of a data frame: using []
WHO[1:3, "Country"]
WHO[1:4, 1]
Observe that “Country” is the first variable in the “WHO” data frame.
22/26
Retrieve part of a data frame: using $
head(WHO$Country, 5)
Note: the “5” after the comma specifies how many observations to display.
23/26
Save R script
24/26
Save objects
When you quit RStudio, you will be asked whether you would like to save
the workspace. You should answer no in general.
• To export CSV:
• To export RData:
25/26
Here are the commands/operators we covered today:
• <-
• c(), seq()
• vector[]
• length(), min(), max(), range(), mean(), sd(), sum()
• setwd(), getwd()
• read.csv(), load()
• str(), names(), nrow(), ncol(), dim(), summary(),
head(), tail(), View()
• write.csv(), save()
• $
26/26