DBMS 1
DBMS 1
Date: ..../....../......
Lab Sheet 1
Familiarization of R Computation
Environment
Aim
• To familiarize with the R computing environment and the basic constructs of
the R programming language, such as, data types, control flow, loops, func-
tions, strings, vectors, matrices and arrays.
Introduction
R is a programming language and a computation environment mainly used for sta-
tistical analysis, data visualization and reporting. It is a widely used programming
language in machine learning, statistics, and data analysis. Though R is a self con-
tained and independent programming language, it also allows us to integrate with
other languages such as C and C++. This labsheet serves as a basic introduction
to the R programming language and the R computation environment.
Examples
Basic Arithmetic in R
x = 2
y = 3
z = x + y
print ( z )
x = TRUE
print ( class ( x ) )
x = 1.234
print ( class ( x ) )
x = 2L
print ( class ( x ) )
x = 2+3 i
print ( class ( x ) )
x = ’c ’
print ( class ( x ) )
Vectors
v = c (1 ,2 ,3)
print ( v )
v1 = c (1 ,4 ,9 ,16 ,25)
print ( v1 )
Figure 3: Vectors
Matrices
M = matrix ( c (1 ,2 ,3 ,4 ,5 ,6) , nrow = 2 , ncol = 3 , byrow = TRUE )
print ( M )
M = matrix ( c (1 ,2 ,3 ,4 ,5 ,6) , nrow = 2 , ncol = 3 , byrow = FALSE )
print ( M )
M = matrix ( c (1 ,2 ,3 ,4 ,5 ,6) , nrow = 2 , ncol = 3)
print ( M )
I = matrix ( c (1 ,0 ,0 ,0 ,1 ,0 ,0 ,0 ,1) , nrow = 3 , ncol = 3)
print ( I )
Figure 4: Matrices
Arrays
A = array ( c (1 ,0 ,0 ,0 ,1 ,0 ,0 ,0 ,1 ,2 ,0 ,0 ,0 ,2 ,0 ,0 ,0 ,2) , dim = c (3 ,3 ,2) )
print ( A )
Figure 5: Arrays
if...else statement
a = 14
if ( is . integer ( a ) ) {
print (" a is an integer ")
} else if ( is . numeric ( a ) ) {
print (" a is numeric ")
} else {
print (" a is neither integer nor numeric ")
}
Switch Statement
x = switch (" color " , " color "=" Red " , " shape "=" circle " ," type "=" good ")
print ( x )
repeat statement
v = c (" Hello " ," Loop ")
counter = 1
repeat {
print ( v )
if ( counter > 5) {
break
}
counter = counter +1
}
x = 0
repeat {
print ( x )
x = x +1
if ( x > 10) {
break
}
counter = 1
while ( counter <20) {
print ( counter )
counter = counter +2
}
Function
avg = mean (1:5)
print ( avg )
x1 = c (3 ,2 ,7 ,1 ,0 ,6 ,9 , -2 ,4)
print ( max ( x1 ) )
print ( min ( x1 ) )
x2 = sum (1:4)
print ( x2 )
User-defined Functions
printSq = function ( max_val ) {
for ( i in 1: max_val ) {
sq = i ^2
print ( sq )
}
return ( sq )
}
printSq (5)
calculate_mean (5 , 10)
The break function stops the loop once it encounters " cherry ".
Evaluation
Participation Knowledge Results Conduct Report Ethics Total