Module 2
Module 2
Looping in R
for loop:
The for loop consists of the following parts: (i) The keyword for,
followed by parentheses; (ii) An identifier between the parentheses
(say i ); (iii) The keyword in, which follows the identifier; (iv) A vector
with values to loop over; and (v) A code block between braces that
has to be carried out for every value in the object values.
if-else:.
An if-else statement contains the same elements as an if statement,
and then some extra: (i) The keyword else, placed after the first code
block; and (ii) A second block of code, contained within braces, that
has to be carried out if and only if the result of the condition in the
if () statement is FALSE.
R data types
R has a wide variety of data types including (but not limited to) the
following. Refer Figure 10.
Matrices and data frames can be reshaped using cbind and rbind
functions.
Facilitator: Dr Sathiya Narayanan S VIT-Chennai - SENSE Fall Semester 2021-22 5 / 128
Module 2: R Programming Basics
R data types
Module-2 Summary
Introduction to R and RStudio
Looping in R: for and if-else
R data types: basic data types (numeric, character, etc), vectors,
matrices and data frames
Processing time computation using proc.time()
9
Control Structure in R
10
Control Structure in R
11
Control Structure in R
IF
if (condition) {
# do something
}
else {
# do something else
}
Example :
x <- 1:15
if (sample(x, 1) <= 10) {
print("x is less than 10")
}
else {
print("x is greater than 10")
}
12
Control Structure in R
If else statement:
x<-5
if(x>1){
print("x is greater than 1")
}
else{
print("x is less than 1")
}
13
Control Structure in R
Vectorization with ifelse
ifelse(x <= 10, "x less than 10", "x greater than 10")
x=10
if(x>1 & x<7){
print("x is between 1 and 7")
}
else if(x>8 & x< 15){
print("x is between 8 and 15")
15
Control Structure in R
for
A for loop works on an itterable variable and assigns successive values
till the end of a sequence.
for (i in 1:10) {
print(i)
}
x <- c("apples", "oranges", "bananas", "strawberries")
for (i in x) {
print(x[i])
}
16
Control Structure in R
for
x = c(1,2,3,4,5)
for(i in 1:5){
print(x[i])
}
o/p
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
17
Control Structure in R
for
for (i in 1:4) {
print(x[i])
}
for (i in seq(x)) {
print(x[i])
}
for (i in 1:4) print(x[i])
18
Control Structure in R
Nested loops
m <- matrix(1:10, 2)
for (i in seq(nrow(m))) {
for (j in seq(ncol(m))) {
print(m[i, j])
19
Control Structure in R
While
i <- 1
while (i < 10) { print(i)
i <- i + 1
}
20
Control Structure in R
Example:
x = 2.987
while(x <= 4.987) {
x = x + 0.987
print(c(x,x-2,x-1))
}
o/p:
21
Control Structure in R
Repeat and break
repeat {
# simulations; generate some value have an expectation if
within some range,
# then exit the loop
if ((value - expectation) <= threshold) {
break
}
}
22
Control Structure in R
Repeat Loop:
The repeat loop is an infinite loop and used in association with a break
statement.
o/p:
[1] 1
[1] 2
[1] 3
[1] 4 23
Control Structure in R
Break Statement
A break statement is used in a loop to stop the iterations and flow the
control outside of the loop.
for (i in 1:20) {
if (i%%2 == 1) {
next
} else
{
print(i)
}
}
This loop will only print even numbers and skip over odd numbers.
25
Control Structure in R
Next
Next statement enables to skip the current iteration of a loop without
terminating it.
for (i in x) {
if(i == 2){
Next
}
print(i)
}
o/p
[1] 1
[1] 3
[1] 4 26
Control Structure in R
Switch Statement
❑ A switch statement permits a variable to be tested in favor of equality
against a list of case values.
❑ In the switch statement, for each case the variable which is being
switched is checked. This statement is generally used for multiple
selection of condition based statement.
Syntax:
27
Control Structure in R
Switch Statement
i=2
gk<-switch (
i,
"First",
"Second",
"Third",
"Fourth")
print (gk)
## [1] "Second"
28
Control Structure in R
29
Control Structure in R
Scan Function
Read data from screen if let the file name "", or just without any parameter:
[1] "43"
30
Control Structure in R
>x <-scan("",what="int")
1: 43 #input 43 from the screen
2: 22
3: 67
4:
Read 3 items
>x
Large data can be scanned in by just copy and paste, for example paste
from EXCEL.
Then use "ctrl+v" to paste the data, the data type will be automatically
determined.
31
Examples #1
Ramu wants to buy a house in an even year, preferably a leap year only. Help him
check if the year is even and a leap year.
#Solution
# Program to check if the input year is a leap year or
not
# Program to check if the input number is odd
year = as.integer(readline(prompt="Enter a year: "))
or even.
if((year %% 4) == 0) {
# A number is even if division by 2 give a
if((year %% 100) == 0) {
remainder of 0.
if((year %% 400) == 0) {
# If remainder is 1, it is odd.
print(paste(year,"is a leap year"))
num = as.integer(readline(prompt="Enter a
} else {
number: "))
print(paste(year,"is not a leap year"))
if((num %% 2) == 0) {
}
print(paste(num,"is Even"))
} else {
} else {
print(paste(year,"is a leap year"))
print(paste(num,"is Odd"))
}
}
} else {
print(paste(year,"is not a leap year"))
}
Example #2
Rahul is learning string manipulation and wants to concatenate strings with and
without separators. He also wants to find the string length before and after
concatenation. Can you help him?
# create a string
string1 <- "Programiz"
# create two strings
string1 <- "Programiz" # use nchar() to find length of string1
string2 <- "Pro" result <- nchar(string1)
The function in turn performs its task and returns control to the interpreter as
well as any result which may be stored in other objects.
Task#2