Module 2:
R Programming
Fundamentals
Objects and Variables: Creating and managing objects.
Core Data Types: numeric, character, logical, integer.
Typecasting: Converting between data types (e.g., [Link]()).
Essential Data Structures: Vectors, Matrices, Lists
Data Frames & Tibbles.
Operators: Arithmetic (+, *), relational (==, >), and logical (&, |, !).
Lahoucine Ech-chatir Data Management & Analysis with R 27
Objects
• Objects are created when you use assign and also created as
the output of functions
• R is object-oriented, so all about objects
R is an object-oriented language: the
variables, data, matrices, functions, results,
etc. are stored in the active memory of
the computer in the form of objects which
• Less formal definition: have a name: one has just to type the
name of the object to display its content.
A virtual thing
• Formal definition:
Everything in R is an object. Something stored in the memory of the programme
with attached value or attributes
Lahoucine Ech-chatir Data Management & Analysis with R 28
1
Objects
Rules for objects
• Cannot begin with a
number e.g. 1object
• Case sensitive e.g.
case ≠ Case
• Cannot be a
fundamental function
e.g. mean
Lahoucine Ech-chatir Data Management & Analysis with R 29
Assign/assigning
• Values are stored by assigning them a name
• The statements
• Use = or <- or ->
Example:
> z = 17
> z <- 17
> 17 -> z
All store the value 17 under the name z in the workspace.
Lahoucine Ech-chatir Data Management & Analysis with R 30
2
Using R as a calculator
• Users type expressions to the R interpreter.
• R responds by computing and printing the answers.
• Arithmetic operators:
Exponents: 5 ^ 2 or 5 ** 2
Lahoucine Ech-chatir Data Management & Analysis with R 31
Using R as a calculator Power multiplication
>3^2
> 2 ^ (-2)
• Arithmetic operators:
Note:
Addition / subtraction > 100 ^ (1/2) Is equivalent to sqrt(100)
>5+5
> 10 - 2 Logarithms
log(5) natural logarithm of 5
Multiplication / division log10(5) base 10 logarithm of 5
> 10 * 10 exp(1) e ^ 1
> 25 / 5
Imaginary numbers
Some special numerical constants: sqrt(-1) = NaN
Inf= infinite, NaN = Not A Number, NA = missing
Additionally basic trigonometry functions
pi sin, cos, tan, asin, acos, atan
The ratio of the circumference of a circle to its
diameter
Lahoucine Ech-chatir Data Management & Analysis with R 32
3
Using R as a calculator
• Logical operators:
Lahoucine Ech-chatir Data Management & Analysis with R 33
Using R as a calculator
• Logical operators
>4<3
[1] FALSE
> 2^3 == 9
[1] FALSE
> (3 + 1) != 3
[1] TRUE
> (3 >= 1) & (4 == (3+1))
[1] TRUE
Lahoucine Ech-chatir Data Management & Analysis with R 34
4
Functions
Stores code that takes an input and gives an output
• Very useful for repeated processes
• Can make our own or use others
• Always outputs objects
• Use arguments
Examples of functions:
sqrt() # takes square root
log() # takes log
exp() # takes exponent
c() # combines values into something called a vector
seq() # creates a sequence of numbers
mean() # takes mean
Lahoucine Ech-chatir Data Management & Analysis with R 35
Arguments
The input to a function
They are given to the function, which does something with them
Example:
Lahoucine Ech-chatir Data Management & Analysis with R 36
5
Data types
● Numeric data are numbers that contain a decimal.
Actually they can also be whole numbers but we’ll
gloss over that.
● Integers are whole numbers (those numbers
without a decimal point).
● Logical data take on the value of either TRUE or
FALSE. There’s also another special type of logical
called NA to represent missing values.
● Character data are used to represent string values.
You can think of character strings as something like a
word (or multiple words).
● Factor data are a special type of character string,
with additional attributes (like levels and an order).
Lahoucine Ech-chatir Data Management & Analysis with R 37
Data types
● class() function will tell you what type an object is
x <- 12
class(x)
## [1] “numeric”
● Logical test to check object class
[Link](x)
## [1] TRUE
[Link](x)
## [1] FALSE
Lahoucine Ech-chatir Data Management & Analysis with R 38
6
Data types
Some useful functions to deal with types
length(object) # Number of elements
str(object) # Structure of an object
class(object) # Class or type of an object
names(object) # Names
as.<typename> # Force to a certain type
is.<typename> # Is of a certain type ?
Lahoucine Ech-chatir Data Management & Analysis with R 39
Typecasting
Sometimes we may want to convert from one data type to another, this is
called “typecasting”
● If R is unable to interpret the data in the requested format, it will return NA
● NA is how R represents missing values
● NAs are “contagious”, meaning that most operations on an NA will return an NA
[Link](1)
> “1”
[Link](“12.0”)
> 12.0
[Link](“A”)
> NA
Lahoucine Ech-chatir Data Management & Analysis with R 40
7
Data Structures – Scalars and Vectors
• Scalar – an object containing a single value
x <- 12
• Vector – an object containing a set of elements, all of the
same class
y <- 0:12
>y
[1] 0 1 2 3 4 5 6 7 8 9 10 11 12
names <- c(“Bob”,”Ralph”,”Mickey”)
>names[2]
[1] “Ralph”
Lahoucine Ech-chatir Data Management & Analysis with R 41
Data Structures – Scalars and Vectors
• Creating numeric vectors
• Creating Factors
1:5 • Recall that Factors are an enumerated character
[1] 1 2 3 4 5 data type
• We can think of these as labels corresponding to
seq(from=1, to=5, by=1) a numeric value
[1] 1 2 3 4 5
> factor(x=c(1,0,1,1,0), levels = 0:1, labels = c("Female",
rep(1,5) "Male"))
[1] 1 1 1 1 1 [1] Male Female Male Male Female
Levels: Female Male
c(4, 2, 3, 1, 5)
[1] 4 2 3 1 5
sort( c(4,2,3,1,5) )
[1] 1 2 3 4 5
Lahoucine Ech-chatir Data Management & Analysis with R 42
8
Data Structures – Matrices and Arrays
● Matrix – an object containing a square matrix of values, all of the
same class
> mymat <- matrix(1:16, nrow = 4, byrow = TRUE)
> my_mat
● Array – a multi-dimensional array
Lahoucine Ech-chatir Data Management & Analysis with R 43
Data Structures – Matrices and Arrays
Creating a matrix:
Lahoucine Ech-chatir Data Management & Analysis with R 44
9
Data Structures – Indexing
Lahoucine Ech-chatir Data Management & Analysis with R 45
Data Structures – Indexing a vector
Lahoucine Ech-chatir Data Management & Analysis with R 46
10
Data Structures – Indexing a matrix
Lahoucine Ech-chatir Data Management & Analysis with R 47
Data Structures - Lists
● Lists are objects which contain other objects of various data types.
> mylist <- list(colours = c("black", "yellow", "orange"),
evaluation = c(TRUE, TRUE, FALSE, TRUE, FALSE, FALSE),
time = matrix(1:6, nrow = 2))
> mylist$colours
[1] "black" "yellow" "orange“
mylist$evaluation
[1] TRUE TRUE FALSE TRUE FALSE FALSE
mylist$time
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
Lahoucine Ech-chatir Data Management & Analysis with R 48
11
Data Structures – Data Frames
● A data frame is a two-dimensional object made up of rows and columns
● Each column within the data frame can be of a different type
● All items must be the same length
> mydata <- [Link](COLOR=c("Black","Yellow","Orange"),
EVALUATION=c(TRUE,TRUE,FALSE),
VALUE=c(1,3,6))
> mydata
COLOR EVALUATION VALUE
1 Black TRUE 1
2 Yellow TRUE 3
3 Orange FALSE 6
Lahoucine Ech-chatir Data Management & Analysis with R 49
Data Structures – Data Frames
● Dimension of data frame
> dim(mydata)
[1] 3 3
● Accessing individual columns
> mydata$COLOR
[1] Black Yellow Orange
Levels: Black Orange Yellow
> mydata[[“VALUE”]]
[1] 1 3 6
● Accessing individual rows
> mydata[2,]
COLOR EVALUATION VALUE
2 Yellow TRUE 3
Lahoucine Ech-chatir Data Management & Analysis with R 50
12
Quick Test
• What is the type of:
• "TRUE"
• "1"
• 1e+11
• #FF00AA
• FALSE
• [Link](TRUE)
• [Link](1e+11)
Lahoucine Ech-chatir Data Management & Analysis with R 51
Exercise
1. Create a vector of the positive odd integers less than 100 (Hint: use
seq function).
2. Remove the values greater than 60 and less than 80.
3. Create a data frame called cone with two elements:
R <- c(2.27, 1.98, 1.69, 1.88, 1.64, 2.14)
H <- c(8.28, 8.04, 9.06, 8.70, 7.58, 8.34)
Recall the volume of a cone with radius R and height H is given by
. Make the third element as V, which is the volume of the
cone.
Lahoucine Ech-chatir Data Management & Analysis with R 52
13
Solution
1. x <- seq(from=1,to=100,by=2)
2. x[x>60&x<80]
3. > R <- c(2.27, 1.98, 1.69, 1.88, 1.64, 2.14)
> H <- c(8.28, 8.04, 9.06, 8.70, 7.58, 8.34)
> V <- 1/3*pi*R^2*H
>V
[1] 44.67974 33.00768 27.09756 32.20057 21.34939 39.99652
> [Link](R,H,V)
Lahoucine Ech-chatir Data Management & Analysis with R 53
Indexing a List: [[ ]]
Lahoucine Ech-chatir Data Management & Analysis with R 54
14
Indexing a List: [[ ]]
The function that allows the creation of a list object is list().
MyList <- list(name="Emmett Brown", wife="Clara Clayton",
[Link]=2, [Link]=c("Giulio","Verne"))
if a component of the list is a vector, one of its elements can be accessed directly
with the syntax:
MyList[[4]] [1]
In this case the output will be "Giulio"
The length() function applied to a list returns the number of its components.
> print(length(MyList))
[1] 4
Lahoucine Ech-chatir Data Management & Analysis with R 55
Indexing a List: [[ ]]
The elements of a list can also be accessed more intuitively by using the name of
the component itself.
The syntax to be used is: list_name$component_name
Both MyList[[1]] and MyList$name return as output:
> MyList$name
[1] "Emmett Brown“
Be careful: it is important to be clear about the difference between MyList[[1]] and
MyList[1]
The operator [[…]] is used for the selection of the single element of the list, while
[…] is used as a general sub-scripting operator.
[[…]] allows the access to an object stored in a list.
Lahoucine Ech-chatir Data Management & Analysis with R 56
15
Index vectors: negative integers
The index vector in this case specifies the elements to be excluded instead of those
to be included by placing a minus – in front of the vector.
> x <- c(10,-5,15,1.2,20,6,3)
> y <- x[-c(1,3:5,length(x))]
> print(y)
[1] -5 6
> print(x[-3])
[1] 10.0 -5.0 1.2 20.0 6.0 3.0
Lahoucine Ech-chatir Data Management & Analysis with R 57
Index vectors and names attributes
This alphanumeric notation (names) is often used to identify the indexes of a
vector, especially in data frames as it is easier to remember than a numerical
indexing.
In the case that an assignment appears together with a sub-selection of elements
of the reference vector x, performed with one of the four described methods, this
assignment is only valid for the elements of vector x selected from the index vector.
x <- c(10,NaN,5,NaN,7,8,NaN); x[[Link](x)] <- 0
print(x)
[1] 10 0 5 0 7 8 0
Lahoucine Ech-chatir Data Management & Analysis with R 58
16
Matrix and [Link] functions
Lahoucine Ech-chatir Data Management & Analysis with R 59
Variables
Variables are boxes
• You can put things in (use: <- or = )
• You can use the box without knowing what is in it
We have already seen them:
Lahoucine Ech-chatir Data Management & Analysis with R 60
17
Character vectors – Strings
Character vectors (strings) are frequently used in R both for the graphic part (plot
labels) and to make the results or the input data of a function more intelligible.
Strings are declared using " " or ' ', but in the console, they are always displayed
using " "
> string1='example1'; string2="example2"
> print(string1)
[1] "example1“
> print(string2)
[1] "example2"
Lahoucine Ech-chatir Data Management & Analysis with R 61
Character vectors – C-style escape sequences
R uses many escape sequences inherited from C.
For example, to display characters in the console that would otherwise be
interpreted differently (such as " and '), use the \ symbol ahead. To start a new line
you can use \n (new line), \tab is the tabular key, \b is the backspace (see ?Quotes)
> string1="Welcome to \"R course\"!"
> cat(string1,"\nSteve Robinson")
Welcome to "R course"!
Steve Robinson
cat() concatenates the character vectors and prints them in console
Lahoucine Ech-chatir Data Management & Analysis with R 62
18
Getting help
Lahoucine Ech-chatir Data Management & Analysis with R 63
Were to go if you are stuck
[Link] Learn R by using R and Rstudio
[Link]
[Link]
[Link]
Lahoucine Ech-chatir Data Management & Analysis with R 64
19