0% found this document useful (0 votes)
3 views16 pages

Introduction to R with Jupyter Notebook

Uploaded by

Adam Nasser
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

Introduction to R with Jupyter Notebook

Uploaded by

Adam Nasser
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to R-Copy1

September 12, 2025

1 STAT 202 - Introduction to R using Jupyter Notebook


In this course we will learn how to perform statistical analyses using R through Jupyter Notebook.
Both R and Jupyter Notebook are open source, meaning that they are free for anyone to download
and use. Users all over the world at many different institutions have contributed thousands of
packages to increase the funcionalities of R. You can install R and Jupyter Notebook on your
own computer if you would like, however, you can also access them all through the University of
Waterloo’s dedicated Jupyter server (where you are now). We suggest using the server.

1.1 Using Jupyter Notebook


Jupyter Notebook provides a way to guide you through coding examples with a mix of text boxes
(like this one!) and fully executable coding boxes. You can identify the coding boxes several ways:
(1) When your cursor is in that box, it will say 'code' in the ribbon above, beside the skip sy
(2) The font is coloured inside of the box
(3) Once executed, there will be "[ ]" beside the box and a number will appear inside of that b
To execute a box of code click on the play symbol in the ribbon above when your cursor is in that
box. The output will appear below the code input.
Note: For this course, we will use Jupyter Notebook so it is not necessary to download
R and RStudio.
You can download R at [Link] R Studio is an “integrated development
environment” (IDE) for R which combines R code, python code, text, latex, and markdown into
a single document (html, pdf, etc.). To use RStudio, you must download it in addition to R. You
can download RStudio here: [Link]

1.2 Getting Started in R


1.2.1 Basic Math
We can use R just like a calculator. We can add, subtract, multiply, divide, raise to a given power,
and use exponentials and logarithms:
[ ]: 1+2

[ ]: 100-35

[ ]: 3*12

1
[ ]: 3^3

[ ]: 2-exp(0.5)+log(20)

The operation inside parentheses take priority over other operations. If you don’t have parentheses
the multiplication and division take priority over subtraction and addition. This why the next two
examples give different results:
[ ]: 1+4/3
(1+4)/3

[ ]: 4*6+5
(4*6)+5
4*(6+5)

R has many numeric functions and every calculation in R is done through functions. Now execute
these basic functions and record the results. For example, sqrt(9) computes the square root of 9;
log(10) computes the natural logarithm of 10; and log10(10) computes the base 10 logarithm of
10; and pi is a built-in constant for 𝜋:
[ ]: sqrt(9)
log(10)
log10(10)
log2(10)
pi

1.2.2 Comments
Comments are lines in R that are not run. You can use them to explain what your code is doing,
or to visually separate chunks of code for easier understanding.
[ ]: # This is a comment.

#------------------------------------------------------------------
# You can use comments to create nice headings between your code
#------------------------------------------------------------------

Notice how #just the things that come after the # sign are commented out.
# Run this cell to see that you will get an error message because R does not␣
↪recognize "Notice how" as a correct code.

Use the next code block to create a comment of your own.


[ ]: # Welcome to Adam's R Notebook

2
1.2.3 Using variables
There are several ways to assign a value to a variable. The valid assignment operators are <- and
= with the former being preferred. Let’s save 2 as the variable x and 3 as the variable z:
[1]: x <- 2
z <- 3

or
[2]: x = 2
z = 3

Note that the spaces around the operator are optional but they do help keep your code more
readable. The assignment operation can be used successively to assign a value to multiple variables
with one line of code. Try this example:
[3]: a <- b <- 7

What are the values of a and b? In order to display or “print” these values, you simply need to
write the name of the variable and then execute the line, for example:
[4]: a
b

7
7
Removing variables in R is done by using the function remove() or its shortcut rm(). Lets remove
the ‘a’ variable and see what happens:
[5]: rm(a)
a

Error in eval(expr, envir, enclos): object 'a' not found


Traceback:

Let’s do an example, assigning values to length, depth, and height to calculate the volume of a
block.
[8]: length <- 5

Now to show what the variable is, we simply type its name:
[9]: length

5
Let’s assign two other variables, depth and height:

3
[10]: depth <- 2
height <- 6

We can use these variables in operations:


[11]: volume <- length * depth * height

[15]: volume

60

Use the next code block to calculate area given the length, depth, and height above.
Note that there are three different ways to calculate the area. Simply pick one to try.
[17]: area <- length * height

[18]: area

30

1.2.4 Data Types


R can store various kinds of data. There are four main types of data: numeric, character (string),
logical, and time. We will focus on the first three. The function class() is used to check the type
of data that are contained in a variable. Try to check the data type for the variable ‘length’ that
you made above.
[19]: # Checking what type of data 'length' is
class(length)

’numeric’

Numeric Data Numeric data handles integers, decimals (both positive and negative), and zeroes.
To test whether a variable is numeric use the function [Link](), and the result will be TRUE
or FALSE. Using this function, check to see if ‘length’ variable is numeric:
[20]: [Link](length)

TRUE
Another important data type that is a subclass of numeric data is the integer. Remember, integers
are whole numbers with no decimals. Assign the integer 5 to the variable g as shown below:
[21]: g <- 5

What results do we get when we print g?


[22]: g

4
To test whether a variable is an integer use the function [Link](). Check if ‘g’ is an integer:

[23]: [Link](g)

FALSE
Neat! To make a variable an integer, you add the capital letter L to end of the value; for example,
3L.

Use the next code block to assign the integer 10 to the variable f and check that it is,
in fact, an integer.
[24]: f <- 10L

[ ]: f

10
[ ]: [Link](f)

TRUE

Character Data The character (string) data type is used for categorical or discrete data in
statistical analysis and should be handled with care. R has two main ways of handling character
data: as characters and as factors. These two categorical data seem similar but should be treated
differently.
Let’s assign the word (i.e., string) “Waterloo” to two new variables, d1 and d2, as character and
factor data types, respectively:
[32]: d1<- "Adam"
d2<- factor("Adam")

[33]: # Print d1 and d2 here


d1
d2

’Adam’
Adam Levels: ’Adam’
When you print d1 you will get ‘Waterloo’ encapsulated in quotes, while d2 contains the word
Waterloo without quotes and has Levels associated with it. The levels of a factor variable represent
the possible unique values (as character strings) contained in or assigned to that variable. We will
discuss factors and levels in more detail when we get to vectors. To find the length of a character
string, the nchar function is used:
[34]: nchar(d1)

5
Write your first name as d1 and last name as d2 and re-run the code blocks above.

Logical Data Logical data can take the values of either TRUE or FALSE. R provides a shortcut
T and F for TRUE and FALSE. Numerically, TRUE is the same as 1 and FALSE is the same as 0. So,
TRUE*2 equals 2 while FALSE*2 equals 0.
Similar to other types of data, variables can be checked to see if they contain logical data using the
function [Link]().

Assign variable k as TRUE, and check the data class for variable k to see if it is logical.

[35]: k <- TRUE

[36]: [Link](k)

TRUE
We can use comparison operators to compare two values. The output of a comparison is either
TRUE or FALSE. Below are examples of commonly used operators in R: - > Greater than - < Less
than - == Equal to - != Not equal to - >= Greater than or equal to - <= Less than or equal to
Here are some examples of a logical result that can be obtained using the comparison operators
with numbers and characters. Think about whether each one should be TRUE/FALSE before you
run the code, and then run the code to verify your answers.
[39]: 3 > 5
3 < 5
4+5 >= 10
3-100 <= 0
3*6 == 18
"eighteen" == "Eighteen"

FALSE
TRUE
FALSE
TRUE
TRUE
FALSE

1.2.5 Vectors
A vector is a collection of elements all of the same data type. We can create a vector using the c()
function in R. For example, a vector of numeric data could be the ages of 5 people in a group: Age
= {20, 15, 22, 17, 18}

[40]: Age <- c(20, 15, 22, 17, 18)


Age

6
1. 20 2. 15 3. 22 4. 17 5. 18
Instead of viewing the entire vector, we can select a certain range and view a subset of the vector
using index. In R, the first element of the vector has index = 1, and the index increases by one.
[41]: # First element:
Age[1]

# Last element:
Age[5]

# 2nd, 3rd, and 4th elements:


Age[2:4]

20
18
1. 15 2. 22 3. 17
Note that vectors don’t have to contain numbers. They can also contain characters or logical values.
[42]: Colours = c("red", "yellow", "blue")
Colours
Logical = c(TRUE, FALSE, TRUE, FALSE)
Logical

1. ’red’ 2. ’yellow’ 3. ’blue’


1. TRUE 2. FALSE 3. TRUE 4. FALSE
Let’s experiment with using some operators on the Age vector. You can perform mathematical
operations on vectors (note that operators are applied on all elements of a vector).

[43]: Double_Age = 2*Age


Double_Age

1. 40 2. 30 3. 44 4. 34 5. 36

In the next text box perform some other operation on the Age vector.
[44]: Age_Two_Years_Ago = Age-2
Age_Two_Years_Ago

1. 18 2. 13 3. 20 4. 15 5. 16
There are additional ways besides the concatenate command (i.e., the c() function) to make a
vector. For example, we can use a colon (:) to make a vector of sequential numbers.

[47]: 1:10
10:1
-2:3
5:-7

7
seq(1,10,by=1)

1. 1 2. 2 3. 3 4. 4 5. 5 6. 6 7. 7 8. 8 9. 9 10. 10
1. 10 2. 9 3. 8 4. 7 5. 6 6. 5 7. 4 8. 3 9. 2 10. 1
1. -2 2. -1 3. 0 4. 1 5. 2 6. 3
1. 5 2. 4 3. 3 4. 2 5. 1 6. 0 7. -1 8. -2 9. -3 10. -4 11. -5 12. -6 13. -7
1. 1 2. 2 3. 3 4. 4 5. 5 6. 6 7. 7 8. 8 9. 9 10. 10
Vector operations can be extended even further. Let’s make two vectors m and n with equal length.
Each of the corresponding elements can be operated on together.
[48]: m <- 1:10
n <- -5:4

Add the two vectors together and record the result:


[49]: m+n

1. -4 2. -2 3. 0 4. 2 5. 4 6. 6 7. 8 8. 10 9. 12 10. 14
Now subtract the two vectors:
[50]: m-n

1. 6 2. 6 3. 6 4. 6 5. 6 6. 6 7. 6 8. 6 9. 6 10. 6
You can also raise one to the power of the other:
[51]: m^n

1. 1 2. 0.0625 3. 0.037037037037037 4. 0.0625 5. 0.2 6. 1 7. 7 8. 64 9. 729 10. 10000


Sometimes it is extremely useful to find out how many elements a vector contains. This is known
as the “length” of the vector. To check the length of a vector, the length() function is used:

[52]: length(m)
length(n)

10
10
Performing operations on two vectors that have different lengths is problematic. The shorter vector
gets recycled, which means its elements are repeated. If the length of the longer vector is not a
multiple of the length of the shorter one, R will give you a warning message. Now let’s try to use
the vector m that has 10 elements and add vectors of unequal length:
[55]: m+c(1,2)
m+c(1,2,3)

8
1. 2 2. 4 3. 4 4. 6 5. 6 6. 8 7. 8 8. 10 9. 10 10. 12
Warning message in m + c(1, 2, 3):
“longer object length is not a multiple of shorter object length”
1. 2 2. 4 3. 6 4. 5 5. 7 6. 9 7. 8 8. 10 9. 12 10. 11

What happens when you try to do each of these operations above?


[56]: #

Vectors can also be compared. Check vector m to see if it is less than or equal to 5:
[57]: m <= 5

1. TRUE 2. TRUE 3. TRUE 4. TRUE 5. TRUE 6. FALSE 7. FALSE 8. FALSE 9. FALSE 10. FALSE
To test whether all elements of a logical vector are TRUE, use the all() function. Use the any()
function to check whether any of the elements are TRUE. Create new vectors x and y. Let’s see if
any or all of x are smaller than y:
[58]: x <- 10:1
y <- -4:5

any(x < y)
all(x < y)

TRUE
FALSE
As mentioned previously in the “Character Data” section, we can create a vector with characters:
[59]: pets <- c("cat", "cat", "dog", "dog", "dog", "fish", "rabbit")
pets

1. ’cat’ 2. ’cat’ 3. ’dog’ 4. ’dog’ 5. ’dog’ 6. ’fish’ 7. ’rabbit’


Let’s turn this character vector into a factor variable to see the different levels. Run the code below
and press the arrow beside “Levels” to view the different levels in ‘[Link]’:
[60]: [Link] <- factor(pets)
[Link]

1. cat 2. cat 3. dog 4. dog 5. dog 6. fish 7. rabbit


Levels: 1. ’cat’ 2. ’dog’ 3. ’fish’ 4. ’rabbit’
The primary use of factor variables is in statistical modeling since categorical variables enter into
statistical models differently than continuous variables. Storing data as factors insures that the
modeling functions will treat such data correctly. It also helps to reduce data redundancy and saves
a lot of space in the memory.

9
1.2.6 Data Frames
A data frame is the bread and butter of R. It is a data structure that can store large amounts
of data. Like Excel spreadsheets, it has rows and columns, where each row is an observation (for
example, a patient in a study) and each column is a variable (for example, age, height, etc.). Data
frames are a collection of vectors, as columns.
Data frames are flexible in that they can contain different types of data (numerical, character,
logical, time) as columns. However, the number of rows in each column must be the same across all
columns. For example, we can’t have a dataframe that contains a column of length 5 and another
column of length 6.
Let’s create our own data frame using the [Link]() function, called PatientData:
[61]: ID_vec1 <- c(1, 2, 3, 4, 5, 6)
Age_vec1 <- c(20, 15, 22, 17, 18, 34)
Height_vec1 <- c(166, 184, 159, 174, 177, 157)

PatientData1 <- [Link](ID = ID_vec1, Age = Age_vec1, Height_cm =␣


↪Height_vec1)

PatientData1

ID Age Height_cm
<dbl> <dbl> <dbl>
1 20 166
2 15 184
A [Link]: 6 × 3
3 22 159
4 17 174
5 18 177
6 34 157
Notice how we defined ID_vec1, Age_vec1 and Height_vec1 as vectors of equal length and created
a data frame using the vectors.
There are several functions in R that we can use with the data frame. The rbind() function
lets us combine two data frames by appending rows of one data frame onto another. Currently,
PatientData1 contains 6 rows, with columns ID, Age and Height_cm. Suppose we have data on 4
extra participants, recorded in the PatientData2 data frame under the same column names. Then,
we can combine these two data frames using the rbind() function to create one large dataframe
containing 10 rows.
[62]: # Creating a new data frame PatientData2 with 4 extra measurements
ID_vec2 <- c(7, 8, 9, 10)
Age_vec2 <- c(25, 26, 16, 18)
Height_vec2 <- c(183, 160, 171, 163)
PatientData2 <- [Link](ID = ID_vec2, Age = Age_vec2, Height_cm =␣
↪Height_vec2)

# Using rbind() function, we row-bind the two data frames together to create a␣
↪new one of length 10

10
PatientData <- rbind(PatientData1, PatientData2)
PatientData

ID Age Height_cm
<dbl> <dbl> <dbl>
1 20 166
2 15 184
3 22 159
4 17 174
A [Link]: 10 × 3
5 18 177
6 34 157
7 25 183
8 26 160
9 16 171
10 18 163
Another function we can use is the cbind() function, which lets us combine two data frames by
columns. Suppose we have a new data frame that contains one column called Respiration that
holds information on a patient’s respiration rate (measured in breaths per minute) with a length
of 10. We can merge this new data frame to PatientData because it also has a length of 10:
[63]: # Create a new data frame ParcitipantData3 that contains information on␣
↪respiration rate

Respiration_vec <- c(10, 8, 16, 35, 20, 19, 14, 10, 25, 22)
PatientData3 <- [Link](Respiration = Respiration_vec)

# Using cbind() funciton, we column-bind two data frames together to create a␣


↪new one

# with 10 rows and 4 columns


PatientData <- cbind(PatientData, PatientData3)
PatientData

ID Age Height_cm Respiration


<dbl> <dbl> <dbl> <dbl>
1 20 166 10
2 15 184 8
3 22 159 16
4 17 174 35
A [Link]: 10 × 4
5 18 177 20
6 34 157 19
7 25 183 14
8 26 160 10
9 16 171 25
10 18 163 22
Since we made some changes to the original data frame, we want to get more information about
the new data frame. With the PatientData data frame, there are only 10 rows and 4 columns, so
we can easily print and view the data. However, how can we get information on a very large data
frame, where it would be unreasonable and inefficient to print and view it entirely?

11
R has multiple built-in functions we can use to get more information about a data frame. The most
common ones are: - nrow(): returns the number of rows - ncol(): returns the number of columns
- names(): returns the column names - head(): prints the first 6 rows - tail(): prints the last 6
rows
[64]: nrow(PatientData)
ncol(PatientData)
names(PatientData)
head(PatientData)
tail(PatientData)

10
4
1. ’ID’ 2. ’Age’ 3. ’Height_cm’ 4. ’Respiration’
ID Age Height_cm Respiration
<dbl> <dbl> <dbl> <dbl>
1 1 20 166 10
2 2 15 184 8
A [Link]: 6 × 4
3 3 22 159 16
4 4 17 174 35
5 5 18 177 20
6 6 34 157 19
ID Age Height_cm Respiration
<dbl> <dbl> <dbl> <dbl>
5 5 18 177 20
6 6 34 157 19
A [Link]: 6 × 4
7 7 25 183 14
8 8 26 160 10
9 9 16 171 25
10 10 18 163 22
We can also access certain parts of the data frame using the following code: -
dataframe$column_name: we use the $ symbol between the name of the data frame and a col-
umn name to return the values in a specific column - dataframe["column_name"]: returns a
specific column - dataframe[ ,x]: returns the x-th column - dataframe[x:y, ]: returns rows x
to y - dataframe[x, y]: returns the value of the element in the x-th row, y-th column
[65]: # Examples of using the functions with our data frame:
PatientData$Respiration

1. 10 2. 8 3. 16 4. 35 5. 20 6. 19 7. 14 8. 10 9. 25 10. 22
[66]: PatientData["Respiration"]

12
Respiration
<dbl>
10
8
16
35
A [Link]: 10 × 1
20
19
14
10
25
22

[67]: PatientData[ ,2]

1. 20 2. 15 3. 22 4. 17 5. 18 6. 34 7. 25 8. 26 9. 16 10. 18
[68]: PatientData[4:7, ]

ID Age Height_cm Respiration


<dbl> <dbl> <dbl> <dbl>
4 4 17 174 35
A [Link]: 4 × 4
5 5 18 177 20
6 6 34 157 19
7 7 25 183 14

[69]: PatientData[9, 1]

9
Similar to performing operations on the vector, we can also perform operations on columns of
data frames. Let’s multiply the numbers in the Age column by 2, and create a new column called
AgeDoubled for these values:

[70]: Double_vec <- PatientData$Age * 2


PatientData$AgeDoubled <- Double_vec

# print the dataframe to view the result


PatientData

13
ID Age Height_cm Respiration AgeDoubled
<dbl> <dbl> <dbl> <dbl> <dbl>
1 20 166 10 40
2 15 184 8 30
3 22 159 16 44
4 17 174 35 34
A [Link]: 10 × 5
5 18 177 20 36
6 34 157 19 68
7 25 183 14 50
8 26 160 10 52
9 16 171 25 32
10 18 163 22 36

Create a new column in the PatientData data frame, called Height_m, that contains
the height in meters. Print the first 6 rows of the dataframe.
[ ]: # Create the new column here

1.2.7 Reading/Writing Data


Reading in Data In this course and real-life scenarios, it is more common to have an external file
containing pre-collected data instead of creating a data frame ourselves. These files are often a CSV
(comma-separated value) file or a text file, but other file types do exist (such as Excel spreadsheets).
To read in the file when you are working with RStudio, you must: 1. Identify where the .csv or
.txt file is located (for example, ~/Desktop/Stat202/). 2. Using the [Link]() or [Link]()
function, load the dataset in R (for example, [Link](~/Desktop/Stat202/[Link])).
However, since we are working in Jupyter Hub, this is easier! In this course, all you need to do is:
1. Upload the .csv file or .txt file onto the Jupyter server, just like how you uploaded this .ipynb
file. 2. No need to identify where the .csv or .txt file is located - you will see it on the left panel.
All you need to do is use the [Link]() or [Link]() function with the file name!
Here is an example using the [Link] dataset. Note that you need to upload the file into the server
in order for the following code to work.
[ ]: # It is convenient to assign a variable name to the loaded dataset
lynx <- [Link]("[Link]")

[ ]: # That way, you can use the `head()` function to view the first 6 rows
head(lynx)

Notice how the code lynx <- [Link]("[Link]") didn’t print anything. It simply ran in the
background until we used the dataset.

Writing Data We can also export the data in R to a .csv file by using the [Link]()function.
Here is an example using the PatientData that we created above.
[ ]:

14
# We first specify what data frame we want to export (PatientData), and to what␣
↪name ([Link])

[Link](PatientData, "[Link]", [Link]=FALSE)

On the left panel, we can now see that there is a [Link] object. Save this file along
with your completed notebook to submit to Crowdmark.

1.2.8 Functions
You have already used several basic functions like nchar(), length(), and [Link]() to extract
information about objects. Almost every step in R uses functions to perform a specific statistical
calculation.
Here are some useful functions that you should be aware of:
• class(): returns the data type of a variable • str(): returns the type of object (i.e., vector, data
frame, etc.) and prints some output • dim(): returns the dimensions of an object • length():
returns the number of elements in an object • min(): returns the minimum valuefor a set of
elements • max(): returns the maximum value for a set of elements • sum(): returns the result
of summing all the elements in the set

Find the min, max, and sum of Age from the dataset PatientData.
[ ]: # Find min, max and sum here

1.2.9 Data Visualization


A good way to understand data is through visual plots, which are especially important when you
have a large dataset. There are several plots we can create in R. These include boxplot, created
using boxplot() function, and stem and leaf plot, created using stem() function.
[ ]: # Create plots using the Age column from PatientData dataset
boxplot(PatientData$Age)
stem(PatientData$Age)

Another plot we can create in R is a histogram, using the hist() command.

Create a histogram of the data in Height_cm column from the PatientData dataset.
[ ]: # create the histogram here

1.2.10 Missing Data


R has two types of missing data: NA and NULL. These are treated differently in R.
NA is seen as another element of the vector. The function [Link]() tests each element of a vector
for this type of missing data. For example:
[ ]: z<-c(1,2,NA,8,3,NA,3)
z
[Link](z)

15
However, the NULL type of missing data is the absence of any data. It is not exactly missing data;
it is more like nothingness. Because NULL is akin to nothingness, it cannot exist within a vector.
If used as an element within a vector, it disappears. For example:
[ ]: z<-c(1,NULL,3)
z

Note that the vector z only has two elements.


The function [Link]() tests for NULL values.
[ ]: d<-NULL
[Link](d)

16

You might also like