0% found this document useful (0 votes)
1 views18 pages

02 Introduction To R Programming

The document is an introduction to R programming, covering basic functions, object types, and how to get help within the R environment. It includes sections on arithmetic operations, R objects, and special operators, along with examples of code execution. Additionally, it provides resources for further learning and support for R users.

Uploaded by

brrk04
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)
1 views18 pages

02 Introduction To R Programming

The document is an introduction to R programming, covering basic functions, object types, and how to get help within the R environment. It includes sections on arithmetic operations, R objects, and special operators, along with examples of code execution. Additionally, it provides resources for further learning and support for R users.

Uploaded by

brrk04
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

Probability Theory and Statistics

Introduction to R Programming

Prof. Gökmen Zararsız

March 16, 2026

Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Basic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Getting Help in R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Comments, spaces, special operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
R Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Object types and classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Data Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Lists(list) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Creating a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Indexing (Lists) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Categorical Variables and Scale Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Working with Date and Time Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

Introduction
In the R software, through the R Console, the codes are executed by typing next to > and pressing ENTER.
However, a new script file can be opened in the RStudio software, the codes are entered in this script file and
the selected code line(s) are executed by clicking the Run button (or ‘Ctrl + ENTER (Windows and Linux),
Cmd + ENTER (Mac OS)’).
The R software can perform arithmetic operations similar to the calculator. The most basic operators are +
for addition, - for subtraction, * for multiplication, and / for division. Also, ˆ is used as the exponentiation
operator, sqrt(...) function is used to get the square root of a value:
17 + 32

## [1] 49
42 * 3 + 5/0.2

## [1] 151
11ˆ2 + sqrt(49)

## [1] 128
Similarly, basic mathematical operations can be done with functions of exp(...), log(...), sin(...),
cos(...), abs(...):

1
Basic Functions Probability Theory and Statistics CONTENTS

exp(3.2)

## [1] 24.53253
log(100)

## [1] 4.60517
log(100, base=10)

## [1] 2
abs(-23)

## [1] 23
sin(pi / 2)

## [1] 1
round(...) function rounds the values to the specified number of decimal places (default 0):
round(log(100), digits = 2)

## [1] 4.61
Here are some of the mathematical functions commonly used in R:

Function What It Does


sqrt(...) Returns the square root. sqrt(2) and 2ˆ(0.5) can be used for same
purposes. ˆ operator
√ can be used to√return specific root values
(e.g. 2ˆ(3/5) for 23 , 9ˆ(1/3) for 3 9).
5

log(...) Takes the logarithm


exp(...) Returns the exponential
abs(...) Takes the absolute value
sin(...), cos(...), . . . Trigonometric functions
round(...), ceiling(...), Rounding functions
floor(...)
sign(...) Sign function (i.e., returning one of values -1, 0 or 1)
... ...

Basic Functions
Session Information: this code shows information about the current R session such as the R version, operating
system, and loaded packages.
sessionInfo()

## R version 4.4.3 (2025-02-28)


## Platform: aarch64-apple-darwin20
## Running under: macOS 26.2
##
## Matrix products: default
## BLAS: /Library/Frameworks/[Link]/Versions/4.4-arm64/Resources/lib/[Link]
## LAPACK: /Library/Frameworks/[Link]/Versions/4.4-arm64/Resources/lib/[Link]; LAPACK ve
##
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Getting Help in R Probability Theory and Statistics CONTENTS

##
## time zone: Europe/Istanbul
## tzcode source: internal
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## loaded via a namespace (and not attached):
## [1] compiler_4.4.3 fastmap_1.2.0 cli_3.6.5 tools_4.4.3
## [5] htmltools_0.5.9 otel_0.2.0 rstudioapi_0.17.1 yaml_2.3.12
## [9] rmarkdown_2.30 knitr_1.51 xfun_0.55 digest_0.6.39
## [13] rlang_1.1.6 evaluate_1.0.5
The dir() function lists all files and folders in the current working directory.
dir()

## [1] "02_Introduction_to_R_Programming_v2.html"
## [2] "02_Introduction_to_R_Programming_v2.log"
## [3] "02_Introduction_to_R_Programming_v2.pdf"
## [4] "02_Introduction_to_R_Programming_v2.Rmd"
## [5] "02_Introduction_to_R_Programming.html"
## [6] "02_Introduction_to_R_Programming.log"
## [7] "02_Introduction_to_R_Programming.pdf"
## [8] "02_Introduction_to_R_Programming.Rmd"
## [9] "[Link]"
The [Link]() function checks whether a specific file exists in the working directory.
It returns TRUE if the file exists and FALSE otherwise.
[Link]("[Link]")

## [1] FALSE
The ls() function lists all objects (variables, datasets, functions) currently stored in the R environment.
ls()

## character(0)
The rm() function removes an object from the R environment.
In this example, the object named a will be deleted.
a = 4
rm("a")

Getting Help in R
R is an easier programming language than other languages. However, to get help with the use of functions
when working with R, a question mark ? is typed at the command line prompt followed by the name of the
function:
?mean

In the Help menu, R Help tab of the R software, there are a number of free sources, including ** An
Introduction to R ’**. Again, it can be practiced online with the R software via the website: https:
//[Link]/resources/training/online-learning/#R. There are also a lot of resources available on the
R website at [Link]
Apart from educational resources, various forums and mailing lists have been created to increase the
communication of R users, to share their knowledge and to seek and offer support for problems encountered

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Comments, spaces, special operators Probability Theory and Statistics CONTENTS

while working with R:


R mailing list: [Link]
R books can be found at [Link]
The R Journal ([Link] can be followed to get up to date information about R.
Here are some other resources:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Some additional modern learning resources for R include:
[Link]
[Link]
[Link]
[Link]

Comments, spaces, special operators


Comments: To comment in R, # operator can be used before writing the comment.
rnorm(n = 100, mean = 10, sd = 2) # A simulated data (n=100) is generated
# under the normal distribution
# with the following parameters: mean = 10, sd = 2.

Using # in the wrong place may the codes and returns errors. All codes, which are written in the same line
after #, are considered as comments.
rnorm(10, 0, # 1)
1)

## [1] -0.5830847 0.1250842 0.1996416 -0.7053952 0.1465572 -0.2347662


## [7] 1.2158345 1.2528455 0.4030042 0.6230918
Spacing: In most cases, the amount of spaces used in R commands has no effect on the results.
rnorm(n = 3, sd = 5,mean = 2)

## [1] 8.992273 1.711038 2.077964


However, the spaces used in the text affect the result.
text1 <- "Lorem ipsum dolor sit amet ..."
text2 <- "Lorem ipsum dolor sit amet ... "

list(Text1 = text1, Text2 = text2)

## $Text1
## [1] "Lorem ipsum dolor sit amet ..."
##
## $Text2
## [1] "Lorem ipsum dolor sit amet ... "

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


R Objects Probability Theory and Statistics CONTENTS

Line breaks: Breaking a line (or several lines) has no effect on the results unless a linebreak was added via
semicolon.
# Below code lines returns identical results.
log(5, base = 3)

## [1] 1.464974
log(5,

base = 3)

## [1] 1.464974
# Try it yourself. What happens now?
log(5); +
log(3)

log(5) + ;
log(3)

Special operators: As in every programming language, some operators are reserved for special functions in
R software.

Operator Function
$ Used to select specific elements in list, matrix and [Link] typed
objects.
% Used for matrix operations.
[...], [[...]] Used to select, or subset, data from a vector, matrix, list or data frame.
{...} Used to denote a block of code in functions, if ... else ... statements,
etc.
(...) Used to specify the function parameters.
! Logical NOT.
&, && Logical AND.
|, || Logical OR.
: Used to generate regular sequences. E.g. 1:10, 4:9, 100:60.
; Used to separate commands. E.g. x <- 5; y <- "Female"

R Objects
R is an object oriented programming language and the results are stored in objects. = or <- symbols are used
to define objects. New objects can be generated by mathematical operations performed on created objects.
Objects are case-sensitive and object names should not contain Turkish characters such as “ç,ğ”. In addition,
when naming objects, special characters and spaces should not be used, and object names should not start
with numbers. Two objects are created and named as a and b. Then, a new c object is created by gathering
a and b objects:
a = 4
b = -7
c = a + b
c

## [1] -3
x = a * c
x

## [1] -12

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Object types and classes Probability Theory and Statistics CONTENTS

When X is executed instead of x, R will return an error since it does not recognize this object. The objects
stored in the computer can be viewed with the objects(...) function:
objects()

## [1] "a" "b" "c" "text1" "text2" "x"


The collection of the objects are names as workspace. The objects can be saved with the save(...)
function, can be loaded with the load(...) function:
save(a, b, c, file = "[Link]")
load("[Link]")

Object types and classes


• Scalar : A vector with only one element (e.g. 3, 5, “Female”, TRUE, etc.)
• Vectors: A basic data structure which contains the same type of data. (e.g. row vector, column vector,
etc.)
• Matrices: A n x p dimensional data structure formed by multiple row or column vectors. All elements
in matrices and vectors must be of the same type (e.g. numerical vector, integer vector, logical
vector, etc.)
• Arrays: A data structure with more than two dimensions formed by multiple row or column vectors.
• Data Frames: A n x p dimensional data structure formed by a combination of different types of
column vectors. This format is frequently used in data analysis.
• Lists: Objects that can consist of different structures in each element. The first element of the list can
be a vector, the second element can be a matrix, and another element can be a data frame. With this
feature, lists are objects where different types of elements can be found together.
• Functions: A set of R statements organized together to perform a specific task.

Vectors
R provides many convenience to work with objects. For example, multiple values can be stored in an object
and all elements of the object can be processed with a single function of interest. The numbers 1 through 7
are stored in an object in the vector class, and then two different operations have been applied to this object.
y = c(1, 2, 3, 4, 5, 6, 7)
y

## [1] 1 2 3 4 5 6 7
10 * y - 3

## [1] 7 17 27 37 47 57 67
yˆ2

## [1] 1 4 9 16 25 36 49
Consecutive and repetitive sequences can be generated using seq(...) and rep(...) functions:
a = 1:5
a

## [1] 1 2 3 4 5
b = seq(-7,12,3)
b

## [1] -7 -4 -1 2 5 8 11

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Vectors Probability Theory and Statistics CONTENTS

c = rep(7,10)
c

## [1] 7 7 7 7 7 7 7 7 7 7
d = c(a, b, c)
d

## [1] 1 2 3 4 5 -7 -4 -1 2 5 8 11 7 7 7 7 7 7 7 7 7 7
Using the length(...) function, the number of elements of the corresponding vector can be obtained:
length(d)

## [1] 22
Numerous descriptive statistics such as arithmetic mean, standard deviation, and median can be obtained
over a vector. For example, descriptive statistics for daily temperature measurements from 8 days can
be calculated as follows:
temperature = c(2.3, 3.6, 4.7, 5.8, 2.3, 10.1, 6.5, 2.2)
mean(temperature)

## [1] 4.6875
median(temperature)

## [1] 4.15
sd(temperature)

## [1] 2.740927
sum(temperature)

## [1] 37.5
min(temperature)

## [1] 2.2
max(temperature)

## [1] 10.1
summary(temperature)

## Min. 1st Qu. Median Mean 3rd Qu. Max.


## 2.200 2.300 4.150 4.688 5.975 10.100
Vector elements can be called with the help of square brackets [ ]:
temperature[2]

## [1] 3.6
temperature[4:7]

## [1] 5.8 2.3 10.1 6.5


temperature[-3]

## [1] 2.3 3.6 5.8 2.3 10.1 6.5 2.2


As in the numerical class, vectors can also be defined in character and logical classes.

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Vectors Probability Theory and Statistics CONTENTS

group = c("city", "city", "city", "city", "country", "country", "country", "country")


group

## [1] "city" "city" "city" "city" "country" "country" "country"


## [8] "country"
table(group)

## group
## city country
## 4 4
tmp = temperature < 5
tmp

## [1] TRUE TRUE TRUE FALSE TRUE FALSE FALSE TRUE


tmp2 = (group == "country")
tmp2

## [1] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE


class(temperature)

## [1] "numeric"
class(group)

## [1] "character"
class(tmp)

## [1] "logical"
Logical operators can be combined with | and &. | can be used for logical “or” operators, & can be used for
logical “and” operators:
tmp | tmp2

## [1] TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE


tmp & tmp2

## [1] FALSE FALSE FALSE FALSE TRUE FALSE FALSE TRUE


It is possible to operate on different vectors using logical operators:
temperature[tmp]

## [1] 2.3 3.6 4.7 2.3 2.2


temperature[group == "city"]

## [1] 2.3 3.6 4.7 5.8


Logical operators result as TRUE orFALSE.

Function What It Does


== Equal to
!= Not equal to
< Less than
<= Less than or equal to

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Matrices Probability Theory and Statistics CONTENTS

Function What It Does


> Greater than
>= Greater than or equal to
& And
| Or

Matrices
Only one variable can be used with vectors. Multiple vectors in the same class (numeric, character, logical)
can be stored in tabular format within the matrix classes. For instance, we can define the age (years), weight
(kg), height (cm), and weekly study hours of five students as vectors; then store them in a matrix class using
the cbind(...) or rbind(...) functions:
age = c(37, 61, 39, 41, 51)
weight = c(57, 90, 60, 97, 90)
height = c(154, 149, 197, 162, 197)
study_hours = c(12, 8, 6, 15, 10)

data1 = cbind(age, weight, height, study_hours)


data1

## age weight height study_hours


## [1,] 37 57 154 12
## [2,] 61 90 149 8
## [3,] 39 60 197 6
## [4,] 41 97 162 15
## [5,] 51 90 197 10
data2 = rbind(age, weight, height, study_hours)
data2

## [,1] [,2] [,3] [,4] [,5]


## age 37 61 39 41 51
## weight 57 90 60 97 90
## height 154 149 197 162 197
## study_hours 12 8 6 15 10
Row and column names in matrices can be defined with rownames(...) and colnames(...) functions,
respectively:
rownames(data1) = c("sample1", "sample2", "sample3", "sample4", "sample5")
data1

## age weight height study_hours


## sample1 37 57 154 12
## sample2 61 90 149 8
## sample3 39 60 197 6
## sample4 41 97 162 15
## sample5 51 90 197 10
colnames(data2) = rownames(data1)
data2

## sample1 sample2 sample3 sample4 sample5


## age 37 61 39 41 51
## weight 57 90 60 97 90
## height 154 149 197 162 197

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Matrices Probability Theory and Statistics CONTENTS

## study_hours 12 8 6 15 10
The transpose of the matrix can be obtained with t(...) function. The dimension of the matrices can be
obtained with dim(...) function. For example, the data2 object is a 4x5 (4 rows, 5 columns) matrix.
t(data2)

## age weight height study_hours


## sample1 37 57 154 12
## sample2 61 90 149 8
## sample3 39 60 197 6
## sample4 41 97 162 15
## sample5 51 90 197 10
dim(data2)

## [1] 4 5
dim(t(data2))

## [1] 5 4
Square brackets [ ] can be used for element operations of the matrices. But this time, both rows and columns
should be specified in square brackets. For [ , ], the part before the comma represents the row elements,
and the part after the comma is the column elements:
data1[1,1]

## [1] 37
data1[3,4]

## [1] 6
data1[2,]

## age weight height study_hours


## 61 90 149 8
data1[,4]

## sample1 sample2 sample3 sample4 sample5


## 12 8 6 15 10
data1[-1,]

## age weight height study_hours


## sample2 61 90 149 8
## sample3 39 60 197 6
## sample4 41 97 162 15
## sample5 51 90 197 10
data1[,-2:-3]

## age study_hours
## sample1 37 12
## sample2 61 8
## sample3 39 6
## sample4 41 15
## sample5 51 10
Matrices can also be created at once with the help of the matrix(...) function. See ?matrix for further
details:

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Data Frames Probability Theory and Statistics CONTENTS

data <- matrix(


c(37, 61, 39, 41, 51,
57, 90, 60, 97, 90,
154, 149, 197, 162, 197,
12, 8, 6, 15, 10),
nrow = 4,
ncol = 5,
byrow = TRUE,
dimnames = list(
c("age", "weight", "height", "study_hours"),
c("sample1", "sample2", "sample3", "sample4", "sample5")
)
)

print(data)

## sample1 sample2 sample3 sample4 sample5


## age 37 61 39 41 51
## weight 57 90 60 97 90
## height 154 149 197 162 197
## study_hours 12 8 6 15 10
class(data)

## [1] "matrix" "array"


Basic graphical operations can be done with plot(...) function:
14
12
t(data)[, 4]

10
8
6

60 70 80 90

t(data)[, 2]

Data Frames
In matrix class, multiple vectors of the same class can be stored. In a data frame, it is possible to store more
than one vector belonging to different types of classes. Statistical analyses in R are usually performed using
objects in the data frame class. This is because a data frame can store both qualitative (nominal, ordinal)

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Data Frames Probability Theory and Statistics CONTENTS

and quantitative (discrete, continuous) data types. The [Link](...) function is used for this purpose.
age = c(37, 61, 39, 41, 51)
weight = c(57, 90, 60, 97, 90)
height = c(154, 149, 197, 162, 197)
study_hours = c(12, 8, 6, 15, 10)

gender = c(rep("female", 3), rep("male", 2))


gender

## [1] "female" "female" "female" "male" "male"


education_level = c(rep("undergraduate", 2), rep("graduate", 3))
education_level

## [1] "undergraduate" "undergraduate" "graduate" "graduate"


## [5] "graduate"
DATA = [Link](age, gender, weight, height, education_level, study_hours)
DATA

## age gender weight height education_level study_hours


## 1 37 female 57 154 undergraduate 12
## 2 61 female 90 149 undergraduate 8
## 3 39 female 60 197 graduate 6
## 4 41 male 97 162 graduate 15
## 5 51 male 90 197 graduate 10
class(DATA)

## [1] "[Link]"
The DATA object in data frame class contain both factor (qualitative in statistical terminology) and numeric
(quantitative in statistical terminology) data.
str(DATA)

## '[Link]': 5 obs. of 6 variables:


## $ age : num 37 61 39 41 51
## $ gender : chr "female" "female" "female" "male" ...
## $ weight : num 57 90 60 97 90
## $ height : num 154 149 197 162 197
## $ education_level: chr "undergraduate" "undergraduate" "graduate" "graduate" ...
## $ study_hours : num 12 8 6 15 10
summary(DATA)

## age gender weight height


## Min. :37.0 Length:5 Min. :57.0 Min. :149.0
## 1st Qu.:39.0 Class :character 1st Qu.:60.0 1st Qu.:154.0
## Median :41.0 Mode :character Median :90.0 Median :162.0
## Mean :45.8 Mean :78.8 Mean :171.8
## 3rd Qu.:51.0 3rd Qu.:90.0 3rd Qu.:197.0
## Max. :61.0 Max. :97.0 Max. :197.0
## education_level study_hours
## Length:5 Min. : 6.0
## Class :character 1st Qu.: 8.0
## Mode :character Median :10.0
## Mean :10.2

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Lists(list) Probability Theory and Statistics CONTENTS

## 3rd Qu.:12.0
## Max. :15.0
Data elements can be called with [ ] square brackets. However, since columns often represent variables in
the data frames, the columns are of greater importance. The data for variables can be called using variable
names or $ character:
DATA[,4]

## [1] 154 149 197 162 197


DATA[,"height"]

## [1] 154 149 197 162 197


DATA$height

## [1] 154 149 197 162 197


How to create data frames in R software? Data frames can be entered into spreadsheets in R software
in a similar way to programs like Excel and SPSS. At this stage, the fix(...) function can be used. In the
opened data editor, variable names can be given, type of the variables can be defined and the data can be
entered:
DATA2 = [Link]()
#fix(DATA2)

Lists(list)
• One of the most preferred structures in the R programming language.
• It can store objects of different structures (vector, data frame, matrix, list, function, etc.).
• The results of functions are mostly returned as lists. Lists differ from data frame structures in that
they can contain elements consisting of vectors with different dimensions.

Creating a List
To combine different objects within an R list and create a list, the list(...) function is used. * List
elements can be used either named within the list or directly as unnamed objects.
[Link](1232)
x <- rnorm(10)
y <- matrix(runif(32, 10, 20), nrow = 8, ncol = 4, byrow = TRUE)
z <- diag(5)

myList <- list(x, y, z) # unnamed list


myList2 <- list(NormalData = x, UniformMatrix = y, DiagonalMatrix = z) # named list

names(myList)

## NULL
names(myList2)

## [1] "NormalData" "UniformMatrix" "DiagonalMatrix"

Indexing (Lists)
Indexing in lists is similar to that in data frame structures. Indexing in a named/unnamed list:

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Lists(list) Probability Theory and Statistics CONTENTS

## Let's use the previously created **"myList"** and **"myList2"** lists.

myList2$NormalData

## [1] 1.52887061 1.30737480 0.91634938 -0.54303574 -0.83473370 -2.04322966


## [7] -0.54733904 -0.09702678 -0.70893648 -1.82512229
myList2[["NormalData"]] # Unlike a **data frame**, two square brackets **`[[ ]]`** are used.

## [1] 1.52887061 1.30737480 0.91634938 -0.54303574 -0.83473370 -2.04322966


## [7] -0.54733904 -0.09702678 -0.70893648 -1.82512229
myList2[[1]] ## **Indexing in unnamed lists.**

## [1] 1.52887061 1.30737480 0.91634938 -0.54303574 -0.83473370 -2.04322966


## [7] -0.54733904 -0.09702678 -0.70893648 -1.82512229
Adding new elements to lists:
[Link](2821)
beta <- rbeta(n = 10, shape1 = 3, shape2 = 5) ## Random data from "Beta Distribution"

myList2[[4]] <- beta ## The list index for assignment should be carefully determined.
myList2$NewData <- beta
myList2[["NewData2"]] <- beta

print(myList2)

## $NormalData
## [1] 1.52887061 1.30737480 0.91634938 -0.54303574 -0.83473370 -2.04322966
## [7] -0.54733904 -0.09702678 -0.70893648 -1.82512229
##
## $UniformMatrix
## [,1] [,2] [,3] [,4]
## [1,] 18.25465 13.81468 16.82927 10.60525
## [2,] 17.77785 17.74960 11.66105 16.93598
## [3,] 19.71063 11.40720 11.20840 16.76967
## [4,] 17.27550 11.41690 15.28013 14.20155
## [5,] 10.18730 19.89837 13.53910 11.15977
## [6,] 17.01647 11.04955 12.09772 15.48134
## [7,] 14.44874 13.57463 15.67389 18.85633
## [8,] 16.13452 19.60833 11.66986 11.73076
##
## $DiagonalMatrix
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 0 0 0 0
## [2,] 0 1 0 0 0
## [3,] 0 0 1 0 0
## [4,] 0 0 0 1 0
## [5,] 0 0 0 0 1
##
## [[4]]
## [1] 0.3845161 0.1579755 0.2677950 0.2595492 0.6925043 0.4166371 0.3626515
## [8] 0.5267124 0.1734540 0.3332316
##
## $NewData

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Lists(list) Probability Theory and Statistics CONTENTS

## [1] 0.3845161 0.1579755 0.2677950 0.2595492 0.6925043 0.4166371 0.3626515


## [8] 0.5267124 0.1734540 0.3332316
##
## $NewData2
## [1] 0.3845161 0.1579755 0.2677950 0.2595492 0.6925043 0.4166371 0.3626515
## [8] 0.5267124 0.1734540 0.3332316
Merging Lists and Adding a NULL Element to a List: * The list() function is used to create an
empty list. * Different lists can be merged into a single list using the append(...) function. However, this is
not the only function available for merging lists; alternative libraries and functions can also be used.
list1 <- list(UpperCase = LETTERS)
list2 <- list(LowerCase = letters)

list3 <- append(list1, list2)


print(list3)

## $UpperCase
## [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
## [20] "T" "U" "V" "W" "X" "Y" "Z"
##
## $LowerCase
## [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
## [20] "t" "u" "v" "w" "x" "y" "z"
Question 1: Add a NULL element to the empty list created below.
emptyListe <- list()

append(emptyListe, NULL) # Method 1

## list()
emptyListe[[1]] <- NULL # Method 2
emptyListe[1] <- NULL # Method 3
emptyListe["empty"] <- NULL
emptyListe[["empty"]] <- NULL

Question 2: Replace an element of the list created below with a NULL element.
liste <- list(Name = "R Introduction")

liste[[1]] <- NULL # Method 1


liste[1] <- NULL # Method 2
liste["Name"] <- NULL
liste[["Name"]] <- NULL

Attention: When modifying lists, data frames, matrices, etc., replacing a row/column or an element with
NULL must be done carefully. If a NULL object is added, you may lose entire rows, columns, or elements.

Function What It Does


length(...) Size of the list (number of elements)
setNames(...),names(...) Naming list elements
[Link](...),[Link](...) Checking list structure and list transformations
lapply(...), mapply(...) Applying a function/operation to list elements
append(...), c(...) Combining lists
... ...

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Categorical Variables and Scale TypesProbability Theory and Statistics CONTENTS

[Link](1232)
x <- rnorm(10)
y <- matrix(runif(32, 10, 20), nrow = 8, ncol = 4, byrow = TRUE)
z <- diag(5)

myList <- list(x, y, z)


names(myList) <- c("one", "two", "three") ## Changes the name of the current list stored in memory.
## No list is returned as a result of the operation.

# It returns the list after renaming it.


# The resulting list must be saved again after this operation.
# Otherwise, no direct changes will be made to the list in memory.
newList <- setNames(object = myList, nm = c("one", "two", "three"))

[Link](myList = names(myList), myList2 = names(newList))

## myList myList2
## 1 one one
## 2 two two
## 3 three three

Categorical Variables and Scale Types


Categorical variables represent qualitative data. These variables can be nominal (no natural order) or
ordinal (have a natural order).
In R, categorical variables are usually represented using factors. Factors can also be defined as ordered if
the categories have a meaningful ranking.
In the following example, different education levels are defined and converted into an ordered factor.
education <- c("primary", "secondary", "bachelor", "master", "phd")

# Check if the object is a vector


[Link](education)

## [1] TRUE
# Check the data type of the vector
typeof(education)

## [1] "character"
# Create an ordered factor
a <- factor(education,
levels = c("primary", "secondary", "bachelor", "master", "phd"),
ordered = TRUE)

## [1] primary secondary bachelor master phd


## Levels: primary < secondary < bachelor < master < phd
# Another way to create an ordered factor
ordered(education, levels = c("primary", "secondary", "bachelor", "master", "phd"))

## [1] primary secondary bachelor master phd


## Levels: primary < secondary < bachelor < master < phd

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Probability Theory and Statistics
Working with Date and Time Variables CONTENTS

Explanation
• [Link]() checks whether the object is a vector.
• typeof() returns the underlying data type of the object.
• factor() converts a character vector into a categorical variable.
• levels defines the categories and their order.
• ordered = TRUE indicates that the categories have a natural ranking (ordinal scale).
• ordered() is another function used to create ordered factors.

Working with Date and Time Variables


Date and time variables are common in many datasets. However, dates may appear in different formats.
The lubridate package in R makes it easier to parse and convert date formats into proper date objects.
# [Link]("lubridate") # Run once if the package is not installed
library(lubridate)

##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
df_one <- [Link](
age = c(10, 11, 30),
height = c(120, 140, 160),
birth_date = c("20100201", "20110522", "20090430")
)

df_two <- [Link](


age = c(10, 11, 30),
height = c(120, 140, 160),
birth_date = c("2010_02_01", "2011_05_22", "2009_04_30")
)

df_three <- [Link](


age = c(10, 11, 30),
height = c(120, 140, 160),
birth_date = c("01022010", "22052011", "30042009")
)

# Examine the structure of the data frame


str(df_one)

## '[Link]': 3 obs. of 3 variables:


## $ age : num 10 11 30
## $ height : num 120 140 160
## $ birth_date: chr "20100201" "20110522" "20090430"
# Convert character dates to Date format
ymd("20110522")

## [1] "2011-05-22"
df_one$birth_date <- ymd(df_one$birth_date)

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group


Probability Theory and Statistics
Working with Date and Time Variables CONTENTS

# Example of another date format


mdy("11-09-1987")

## [1] "1987-11-09"
Explanation
• lubridate is a package that simplifies working with date and time variables.
• str() shows the structure of the data frame and variable types.
• ymd() converts dates in year-month-day format to Date objects.
• mdy() converts dates in month-day-year format.
After conversion, the date variable becomes a Date class, which allows easier manipulation and analysis of
time-related data.

Copyright © 2026 Precision Medicine and Advanced Analytics Research Group

You might also like