02 Introduction To R Programming
02 Introduction To R Programming
Introduction to R Programming
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:
Basic Functions
Session Information: this code shows information about the current R session such as the R version, operating
system, and loaded packages.
sessionInfo()
##
## 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
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)
## $Text1
## [1] "Lorem ipsum dolor sit amet ..."
##
## $Text2
## [1] "Lorem ipsum dolor sit amet ... "
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
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()
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
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)
## [1] 3.6
temperature[4:7]
## group
## city country
## 4 4
tmp = temperature < 5
tmp
## [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
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)
## 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)
## [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 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:
print(data)
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)
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)
## [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)
## 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]
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)
names(myList)
## NULL
names(myList2)
Indexing (Lists)
Indexing in lists is similar to that in data frame structures. Indexing in a named/unnamed list:
myList2$NormalData
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
## $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()
## 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")
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.
[Link](1232)
x <- rnorm(10)
y <- matrix(runif(32, 10, 20), nrow = 8, ncol = 4, byrow = TRUE)
z <- diag(5)
## myList myList2
## 1 one one
## 2 two two
## 3 three three
## [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)
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.
##
## 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")
)
## [1] "2011-05-22"
df_one$birth_date <- ymd(df_one$birth_date)
## [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.