0% found this document useful (0 votes)
65 views30 pages

R Module 2

This document discusses core programming principles in R, including functions, vectors, matrices, data frames, and logical statements. It provides examples of using built-in datasets, generating sequences and factors, appending and slicing vectors, and using if, else, and if/else statements. Functions allow input through parentheses while packages provide additional functions. Logical operators like & and | are used to compare vectors and make conditional comparisons.

Uploaded by

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

R Module 2

This document discusses core programming principles in R, including functions, vectors, matrices, data frames, and logical statements. It provides examples of using built-in datasets, generating sequences and factors, appending and slicing vectors, and using if, else, and if/else statements. Functions allow input through parentheses while packages provide additional functions. Logical operators like & and | are used to compare vectors and make conditional comparisons.

Uploaded by

Damai Arum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Core Programming Principle: Object

Operation and Logical Statement in R


Jesita Wida Ajani, S.E.
Table of Content
1. Introduction of Function
2. Vector, Vectorized Operations
3. Appending Vector
4. Slicing Vector
5. Using the [] Brackets
6. Functions and Packages in R
7. And & Or
8. If, else, and If else
Using Built in Dataset
• R has a bunch variety of embedded datasets, we can access them
through data() function
• These datasets are very helpful to building skills particularly in R.
data(mtcars)
## using data function while giving the dataset name and package name
data(Cars93, package=“MASS”)

• You can see the available built-in data in R from this website:
https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/
Introduction of Function
• Functions in R is determined by sign “()” for the input. Most of it has
more than 1 input, for example:
seq(from=1, to=15, by=2)
## [1] 1 3 5 7 9 11 13 15
• There are tons of packages including outsourcing packages for certain
occasions, the next fews module will comprehensively explain about
it.
Introduction of Function
• Regular Sequence
The function seq can generate sequences of real numbers as follows:
seq(10,200,5)
[1] 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115
[23] 120 125 130 135 140 145 150 155 160 165 170 175 180 185 190 195 200
• Replication
> rep(1,4)
[1] 1 1 1 1
Introduction to Function
• The function gl (generate levels) is very useful because it generates regular series of
factors. The usage of this fonction is gl(k, n) where k is the number of levels (or
classes), and n is the number of replications in each level. Two options may be used:
length to specify the number of data produced, and labels to specify the names of the
levels of the factor. Examples:
> gl (2,5)
[1] 1 1 1 1 1 2 2 2 2 2
Levels: 1 2
> gl (2,5,length=10)
[1] 1 1 1 1 1 2 2 2 2 2
Levels: 1 2
> gl (2,5,length=11)
[1] 1 1 1 1 1 2 2 2 2 2 1
Levels: 1 2
Vectors
• The properties of vectors
1. Vectors are homogeneous (have the same type;)
2. Vectors can be indexed by position;
v[2] refers to the second element of v

3. Vectors can be indexed by multiples positions, returning a


subvector;
v[c(1,2)] refers to the first and second elements of vector v

4 Vector elements can have names


Matrices
• Matrices is a vector or list with more dimensions, for example:
a <- 1:6
dim(a)
## [1] NULL
• We give dimensions to the vector by using dim():
dim(a) <- c(2,3) ## reshaping into 2 x 3 matrix
print(a)
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
Data Frame
• Data frame is powerful and flexible structure. Almost every analysis in
R involves data frame. It is just like a dataset. There are several
properties of data frame:
1. The elements of the list are vectors and/or factors;
2. Those vectors and factors are the columns of the data frame;
3. The vectors and factors must all have the same length; in other
words, all columns must have the same height;
4. The equal-height columns give a rectangular shape to the data
frame;
5. The columns must have a name
Slicing Vectors and Data Frame
• We can use list operators to extract columns from a vector and data
frame such as df[i], df[[i]], df$name. For example:
1. df[1,] refers to elements in the first row in all columns in object df
2. df[,4] refers to elements in all rows in fourth columns in object df
3. df[c(1,3,5), c(2,4,6)] refers to elements in first, third, and fifth rows
and second, fourth, and sixth columns in object df
4. df[4:9, 5:10] refers to elements in fourth until ninth rows and fifth
until tenth in object df
5. df$cars refers to all elements in columns whose names is “cars” in
object df
Slicing Vectors and Data Frame
• Negative integers do the exact opposite of positive integers
when indexing. R will return every element except the
elements in a negative index. For example:
1. v[-(2:5), 1:3] refers to the element except second until fifth
row in first until third column
Using the [] Brackets
• x <- c(1,120,200,300) #combine
• y <- seq(201, 202, 10) #sequence
• z <- rep(“Hi!”, 3) #replicate
• w <- c(“a”, “b”, “c”)
•w
Try inputting this in R:
• w[1]
• w[-2] #backwards
• w[1:3] #Meaning that we will generate 1,2,3. If we want to access 1
and 2 only, we can type w[c(1,2)]
Appending Data to a Vector
• The most efficient way is to create a new vector using the vector
constructor (c), for example:
v <- c(1,2,3) w <- c(5,6,7,8)
v <- c(v,4) v <- c(v,w)
v v
## [1] 1 2 3 4 ## [1] 1 2 3 4 5 6 7 8
How R handles vectors of unequal length?
• In this case, R invokes the Recycling Rule. It processes the vector
element in pairs. R returns to the beginning of the shorter vector,
“recycling” its elements, for example:
1:6 1:3 (1:6)+(1:3)
1 1 2
2 2 4
3 3 6
4 1 5
5 2 7
Factors
• A factor looks like a vector, but it shares different role. R keeps track
of the unique values in a vector, and each unique value is called a
level of the associated factor.
cars <- c(2:5) Factors is used for two main functions:
cars <- as.factors(cars) 1. Categorical Variables. This features can be
cars used in contingency tables, linear
regression, Analysis of Variance (ANOVA),
## [1] 2 3 4 5
and logistic regression;
levels(cars) 2. Grouping. This is a technique for labelling or
## [1] “2” “3” “4” “5” tagging your data items according to their
group.
Comparing Vectors
• We can use the properties of logical statement to compare two
vectors, for example:
linkedin <- c(16, 9, 13, 5, 2, 17, 14)
facebook <- c(17, 7, 5, 16, 8, 13, 14)
views <- matrix(c(linkedin, facebook), nrow=2, byrow = T)
views == 13
## [,1] [,2] [,3] [,4] [,5] [,6]
##[1,] F F T F F F
##[2,] F F F F T F
& and |
• R evaluates & as “and” and | as “or”, for example:
facebook <- c(16, 9, 13, 5, 2, 17, 14)
last <- tail(facebook,1)
# is last under 5 or above 10?
last < 5 | last > 10
## [1] TRUE
last > 15 & last <= 20
## [1] FALSE
& and |
• Let’s go back to view
# When is views between 11 (exclusive) and 14 (inclusive)?
views > 11 & views <= 14
## [,1] [,2] [,3] [,4] [,5] [,6]
##[1,] F F T F F T
##[2,] F F F F T T
If Statements
• An if statement tells R to do a certain task for a certain case. In English
you would say something like, “If this is true, do that”. In R, you would
say:
if (this){
that
}
• The this object should be a logical test or an R expression that
evaluates to a single TRUE or FALSE, if it is true, R will run all of the
code that appears between the {}. Conversely, R will skip the code.
If Statements
Example:
num <- 4 num <- 4
if (num < 5){ if (num < 3){
num <- num + 1 num <- num + 1
} }
num num
## [1] 5 ## [1] 4
• Both programs evaluate num as a logical expression, in the left side, num is TRUE, so it executes the
codes. On the other hand, in the right side, num is FALSE and it skips the program.
Quiz #1
• What will this return?
x <- 1
if (x <= 10){
x <- (x*2)+10
if (x == 8){
x <- 3
}
}
x
If Else Statements
• If statements tell R what to do when your condition is true, however, you can also
tell R what to do when the condition is false. In this condition we can use else as a
counterpart code. “If this is true, do plan A; else do plan B”.
If (this){
Plan A
} else{
Plan B
}
• When this evaluates to TRUE, R will run the code Plan A. When this evaluates to
FALSE, R will run the code Plan B and not Plan A, we also can use else for more
than one condition by using else if.
If Else Statements
• For example:
b <- 5 b <- 5
if (b < 5){ if (b < 6){
b <- b – 2 b <- b - 2
} else { } else {
b <- b – 1 b <- b - 1
} }
b b
## [1] 4 ## [1] 3
If Else Else If Statement
Example:
num <- 4
if (num < 0){
print(“The number is negative”)
} else if (num > 0){
print(“The number is positive”)
} else {
print(“The number is zero”)
NB: else if put the conditional
## [1] The number is positive statement, and else do not.
Post-tutorial Assignment
Tutorial Assignment
1. Please create a function from 1 to 100 with length of 10 in between
the function.
2. Please create a matrices comprising of 20 to 120 and rename it to
“temp1”. Then, give the vector a dimension of 3x3 matrix.
3. A vector of :
x = c(200,400,600,800)
y = c(20,30,40,50)
a. Please append both vector together to one vector called “xy”
b. If y = c(20,40,50), can we still append the vector with x? If yes, show
the results!
Tutorial Assignment
4. a. Compare these two vectors:
instagram <- c(200,300,500,550,400)
tiktok <- c(200,340,500,550,540)
b. Aside from comparing, please find whether instagram’s fourth
observation is above 500?
You need to submit the Homework to obtain a training certificate!
References
• Https://cran.r-project.org/doc/contrib/Paradis-rdebuts_en.pdf
• Eremenko, Kiriil. (2021, March 5). R For Data Science with Real
Exercise [Video file]. Retrieved from
https://www.udemy.com/course/r-programming/learn/lecture/45857
02#overview
.
• https://www.statmethods.net/input/importingdata.html
Thank You and See you on the next tutorial!

You might also like