0% found this document useful (0 votes)
14 views57 pages

SEE R Practical Dhara

The document provides an index and detailed introduction to R and MATLAB, including their installation, basic syntax, data types, and mathematical functions. R is highlighted for its statistical computing and visualization capabilities, while MATLAB is emphasized for numerical computation and application development. The document also covers practical exercises and examples to illustrate the functionalities of both programming languages.

Uploaded by

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

SEE R Practical Dhara

The document provides an index and detailed introduction to R and MATLAB, including their installation, basic syntax, data types, and mathematical functions. R is highlighted for its statistical computing and visualization capabilities, while MATLAB is emphasized for numerical computation and application development. The document also covers practical exercises and examples to illustrate the functionalities of both programming languages.

Uploaded by

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

INDEX

Sr. No Practical Date Signature


1. R Introduction 29-07-24
2. MATLAB Introduction 05-07-24
3. R and MATLAB Installation 12-07-24
4. R basics and MATLAB math 02-09-24
functions
5. R Data types 09-09-24
6. R Operators 16-09-24
7. R Loops 04-10-24
8. R Conditional statements 04-10-24
9. R Matrices 07-10-24
10. R String 14-10-24
11. R List 21-10-24
12. R Statistical measurements 04-11-24
13. R Function 11-11-24
14. R Charts and Graphs 18-11-24
15. R Reading csv and excel file 19-11-24
1. R Introduction
What is R
R is a popular programming language used for statistical computing
and graphical presentation.
Its most common use is to analyze and visualize data.
Why Use R?
• It is a great resource for data analysis, data visualization, data
science and machine learning
• It provides many statistical techniques (such as statistical tests,
classification, clustering and data reduction)
• It is easy to draw graphs in R, like pie charts, histograms, box
plot, scatter plot, etc++
• It works on different platforms (Windows, Mac, Linux)
• It is open-source and free
• It has a large community support
• It has many packages (libraries of functions) that can be used to
solve different problems

2. MATLAB Introduction
MATLAB (matrix laboratory) is a fourth-generation high-level
programming language and interactive environment for numerical
computation, visualization and programming.
MATLAB is developed by MathWorks.
It allows matrix manipulations; plotting of functions and data;
implementation of algorithms; creation of user interfaces; interfacing
with programs written in other languages, including C, C++, Java, and
FORTRAN; analyze data; develop algorithms; and create models and
applications.
It has numerous built-in commands and math functions that help you
in mathematical calculations, generating plots, and performing
numerical methods.
MATLAB's Power of Computational Mathematics
MATLAB is used in every facet of computational mathematics.
Following are some commonly used mathematical calculations where
it is used most commonly −
• Dealing with Matrices and Arrays
• 2-D and 3-D Plotting and graphics
• Linear Algebra
• Algebraic Equations
• Non-linear Functions
• Statistics
• Data Analysis
• Calculus and Differential Equations
• Numerical Calculations
• Integration
• Transforms
• Curve Fitting
• Various other special functions

Features of MATLAB
Following are the basic features of MATLAB −
• It is a high-level language for numerical computation,
visualization and application development.
• It also provides an interactive environment for iterative
exploration, design and problem solving.
• It provides vast library of mathematical functions for linear
algebra, statistics, Fourier analysis, filtering, optimization,
numerical integration and solving ordinary differential
equations.
• It provides built-in graphics for visualizing data and tools for
creating custom plots.
• MATLAB's programming interface gives development tools for
improving code quality maintainability and maximizing
performance.
• It provides tools for building applications with custom graphical
interfaces.
• It provides functions for integrating MATLAB based algorithms
with external applications and languages such as C, Java, .NET
and Microsoft Excel.
Uses of MATLAB
MATLAB is widely used as a computational tool in science and
engineering encompassing the fields of physics, chemistry, math and
all engineering streams. It is used in a range of applications including

• Signal Processing and Communications
• Image and Video Processing
• Control Systems
• Test and Measurement
• Computational Finance
3. R Installation and MATLAB Installation
To install R, go to https://cloud.r-project.org/ and download the
latest version of R for Windows, Mac or Linux.
When you have downloaded and installed R, you can run R on your
computer.
The screenshot below shows how it may look like when you run R on
a Windows PC:
If you type 5 + 5, and press enter, you will see that R outputs 10.

MATLAB Installation
Local Environment Setup
Setting up MATLAB environment is a matter of few clicks. The
installer can be downloaded from here.
MathWorks provides the licensed product, a trial version and a
student version as well. You need to log into the site and wait a little
for their approval.
After downloading the installer the software can be installed through
few clicks.
Understanding the MATLAB Environment
MATLAB development IDE can be launched from the icon created on
the desktop. The main working window in MATLAB is called the
desktop. When MATLAB is started, the desktop appears in its default
layout −

The desktop has the following panels −


• Current Folder − This panel allows you to access the project
folders and files.

• Command Window − This is the main area where commands


can be entered at the command line. It is indicated by the
command prompt (>>).
• Workspace − The workspace shows all the variables created
and/or imported from files.

4. R basic syntax And Math Functions in MATLAB :-


#Write a code to print Hello, World!
> string<-"Hello, World!"
> print(string)
[1] "Hello, World!"
#print integers from 1 to 10
for (x in 1:10) {
print(x)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Here is different Mathematical functions and their syntax for MATLAB.


• Arithmetic functions

Arithmetic Symbol Operation

+ Addition

– Subtraction

* Multiplication

/ Division

• Trigonometric functions

Trigonometric
Operation / Function
Symbol

sin(t) Performs Sin operation on variable ‘t’.


cos(t) Performs cosine operation on variable ‘t’.

tan(t) Performs tangent operation on variable ‘t’.

Performs arc sin operation on variable ‘t’ or Inverse of the sin


asin(t)
function.

Performs arc cosine operation on variable ‘t’ or Inverse of the cos


acos(t)
function.

Performs arc tangent operation on variable ‘t’ or Inverse of the tan


atan(t)
function.

• Exponential functions

Exponetial Symbol Operation

exp(t) Performs exponential operation on variable ‘t’.

• Square functions

Symbol Operation

^ Power or Square

sqrt(t) Performs square root operation on variable ‘t’.

• Logarithm functions

Symbol Operation

log(t) Performs a natural logarithmic operation on variable ‘t’.

log10(t) Performs a common logarithmic operation on variable ‘t’.

• Maximum & Minimum functions


Symbol Operation

min(t) Finds minimum value from array ‘t’.

max(t) Finds maximum value from array ‘t’.

• Remainder function

Symbol Operation

rem(p,q) Gives the remainder after the dividing ‘p’ by ‘q’.

• Phase angle function

Symbol Operation

angel(t) Gives phase angle for variable ‘t’.

• Other useful functions

Symbol Operation

abs(t) Returns absolute value for variable ‘t’.

sign(t) Returns sign of the variable ‘t’.

ceil(t) Returns ceil value for variable ‘t’.

floor(t) Returns floor value for variable ‘t’.

conj(t) Gives complex conjugate of variable ‘t’.

round(t) Returns nearest integer of variable ‘t’.


5. R Data Types:-
Variables are nothing but reserved memory locations to store values. This
means that, when you create a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory
and decides what can be stored in the reserved memory. The variables are
assigned with R-Objects and the data type of the R-object becomes the data
type of the variable. There are many types of R-objects,
• Vectors
• Lists
• Matrices
• Arrays
• Factors
• Data Frames

Vectors:- The simplest of these objects is the vector object and there are six
data types of these atomic vectors, also termed as six classes of vectors. The
other R-Objects are built upon the atomic vectors.

Data Type Example Verify

Live Demo
v <- TRUE
Logical TRUE, FALSE print(class(v))
it produces the following result −
[1] "logical"

Live Demo
v <- 23.5
Numeric 12.3, 5, 999 print(class(v))
it produces the following result −
[1] "numeric"

Live Demo
v <- 2L
Integer 2L, 34L, 0L print(class(v))
it produces the following result −
[1] "integer"

Live Demo
v <- 2+5i
Complex 3 + 2i print(class(v))
it produces the following result −
[1] "complex"

Live Demo
v <- "TRUE"
Character 'a' , '"good", "TRUE", '23.4' print(class(v))
it produces the following result −
[1] "character"

Live Demo
v <- charToRaw("Hello")
Raw "Hello" is stored as 48 65 6c 6c 6f print(class(v))
it produces the following result −
[1] "raw"

When you want to create vector with more than one element, you should
use c() function which means to combine the elements into a vector.
> apple<- c("red","green","yellow")
> print(apple)
[1] "red" "green" "yellow"
> print(class(apple))
[1] "character"
# create sequence of numbers
> v <- 5:13
> print(v)
[1] 5 6 7 8 9 10 11 12 13

> v <- 6.6:12.6


> print(v)
[1] 6.6 7.6 8.6 9.6 10.6 11.6 12.6

> v <- 3.8:11.4


> print(v)
[1] 3.8 4.8 5.8 6.8 7.8 8.8 9.8 10.8
# access elements from the vector
> t <- c("Sun","Mon","Tue","Wed","Thurs","Fri","Sat")
> u <- t[c(2,3,6)]
> print(u)
[1] "Mon" "Tue" "Fri"
# create two lists and do operations on it
> v1 <- c(3,8,4,5,0,11)
> v2 <- c(4,11,0,8,1,2)
> add.result <- v1+v2
> print(add.result)
[1] 7 19 4 13 1 13
> sub.result <- v1-v2
> print(sub.result)
[1] -1 -3 4 -3 -1 9
> multi.result <- v1*v2
> print(multi.result)
[1] 12 88 0 40 0 22
> divi.result <- v1/v2
> print(divi.result)
[1] 0.7500000 0.7272727 Inf 0.6250000 0.0000000 5.5000000
# sort the elements in order
> v <- c(3,8,4,5,0,11, -9, 304)
> sort.result <- sort(v)
> print(sort.result)
[1] -9 0 3 4 5 8 11 304
> revsort.result <- sort(v, decreasing = TRUE)
> print(revsort.result)
[1] 304 11 8 5 4 3 0 -9
> v <- c("Red","Blue","yellow","violet")
> sort.result <- sort(v)
> print(sort.result)
[1] "Blue" "Red" "violet" "yellow"

List:- A list is an R-object which can contain many different types of elements
inside it like vectors, functions and even another list inside it.
> list1 <- list(c(2,5,3),21.3,sin)
> print(list1)
[[1]]
[1] 2 5 3

[[2]]
[1] 21.3

[[3]]
function (x) .Primitive("sin")

> # Create a list containing a vector, a matrix and a list.


> list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
+ list("green",12.3))
>
> # Give names to the elements in the list.
> names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")
>
> # Show the list.
> print(list_data)
$`1st Quarter`
[1] "Jan" "Feb" "Mar"

$A_Matrix
[,1] [,2] [,3]
[1,] 3 5 -2
[2,] 9 1 8

$`A Inner list`


$`A Inner list`[[1]]
[1] "green"

$`A Inner list`[[2]]


[1] 12.3

> print(list_data[1])
$`1st Quarter`
[1] "Jan" "Feb" "Mar"
> print(list_data$A_Matrix)
[,1] [,2] [,3]
[1,] 3 5 -2
[2,] 9 1 8

# Create two lists.


> list1 <- list(1,2,3)
> list2 <- list("Sun","Mon","Tue")
>
> # Merge the two lists.
> merged.list <- c(list1,list2)
>
> # Print the merged list.
> print(merged.list)
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] "Sun"
[[5]]
[1] "Mon"

[[6]]
[1] "Tue"

Matrices:- A matrix is a two-dimensional rectangular data set. It can be created


using a vector input to the matrix function.
> M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
> print(M)
[,1] [,2] [,3]
[1,] "a" "a" "b"
[2,] "c" "b" "a"

> # Create two 2x3 matrices.


> matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
> print(matrix1)
[,1] [,2] [,3]
[1,] 3 -1 2
[2,] 9 4 6
>
> matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
> print(matrix2)
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
>
> # Add the matrices.
> result <- matrix1 + matrix2
> cat("Result of addition","\n")
Result of addition
> print(result)
[,1] [,2] [,3]
[1,] 8 -1 5
[2,] 11 13 10
>
> # Subtract the matrices
> result <- matrix1 - matrix2
> cat("Result of subtraction","\n")
Result of subtraction
> print(result)
[,1] [,2] [,3]
[1,] -2 -1 -1
[2,] 7 -5 2

> # Create two 2x3 matrices.


> matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
> print(matrix1)
[,1] [,2] [,3]
[1,] 3 -1 2
[2,] 9 4 6
>
> matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
> print(matrix2)
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
>
> # Multiply the matrices.
> result <- matrix1 * matrix2
> cat("Result of multiplication","\n")
Result of multiplication
> print(result)
[,1] [,2] [,3]
[1,] 15 0 6
[2,] 18 36 24
>
> # Divide the matrices
> result <- matrix1 / matrix2
> cat("Result of division","\n")
Result of division
> print(result)
[,1] [,2] [,3]
[1,] 0.6 -Inf 0.6666667
[2,] 4.5 0.4444444 1.5000000
Arrays:- While matrices are confined to two dimensions, arrays can be of any
number of dimensions. The array function takes a dim attribute which creates
the required number of dimensions. In the below example we create an array
with two elements which are 3x3 matrices each.
> a <- array(c('green','yellow'),dim = c(3,3,2))
> print(a)
,,1

[,1] [,2] [,3]


[1,] "green" "yellow" "green"
[2,] "yellow" "green" "yellow"
[3,] "green" "yellow" "green"

,,2

[,1] [,2] [,3]


[1,] "yellow" "green" "yellow"
[2,] "green" "yellow" "green"
[3,] "yellow" "green" "yellow"

Factors:- Factors are the r-objects which are created using a vector. It stores the
vector along with the distinct values of the elements in the vector as labels.
The labels are always character irrespective of whether it is numeric or
character or Boolean etc. in the input vector. They are useful in statistical
modeling.
Factors are created using the factor() function. The nlevels functions gives the
count of levels.
> apple_colors <- c('green','green','yellow','red','red','red','green')
> factor_apple <- factor(apple_colors)
> print(factor_apple)
[1] green green yellow red red red green
Levels: green red yellow
> print(nlevels(factor_apple))
[1] 3

DataFrame:- Data frames are tabular data objects. Unlike a matrix in data
frame each column can contain different modes of data. The first column can
be numeric while the second column can be character and third column can be
logical. It is a list of vectors of equal length.
Data Frames are created using the data.frame() function.
> BMI <- data.frame(
+ gender = c("Male", "Male","Female"),
+ height = c(152, 171.5, 165),
+ weight = c(81,93, 78),
+ Age = c(42,38,26)
+)
> print(BMI)
gender height weight Age
1 Male 152.0 81 42
2 Male 171.5 93 38
3 Female 165.0 78 26

> # Create the data frame.


> emp.data <- data.frame(
+ emp_id = c (1:5),
+ emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
+ salary = c(623.3,515.2,611.0,729.0,843.25),
+
+ start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-
05-11",
+ "2015-03-27")),
+ stringsAsFactors = FALSE
+)
> # Print the data frame.
> print(emp.data)
emp_id emp_name salary start_date
1 1 Rick 623.30 2012-01-01
2 2 Dan 515.20 2013-09-23
3 3 Michelle 611.00 2014-11-15
4 4 Ryan 729.00 2014-05-11
5 5 Gary 843.25 2015-03-27

> str(emp.data)
'data.frame': 5 obs. of 4 variables:
$ emp_id : int 1 2 3 4 5
$ emp_name : chr "Rick" "Dan" "Michelle" "Ryan" ...
$ salary : num 623 515 611 729 843
$ start_date: Date, format: "2012-01-01" "2013-09-23" "2014-11-15" "2014-
05-11" ...

> # Print the summary.


> print(summary(emp.data))
emp_id emp_name salary start_date
Min. :1 Length:5 Min. :515.2 Min. :2012-01-01
1st Qu.:2 Class :character 1st Qu.:611.0 1st Qu.:2013-09-23
Median :3 Mode :character Median :623.3 Median :2014-05-11
Mean :3 Mean :664.4 Mean :2014-01-14
3rd Qu.:4 3rd Qu.:729.0 3rd Qu.:2014-11-15
Max. :5 Max. :843.2 Max. :2015-03-27

> # Extract Specific columns.


> result <- data.frame(emp.data$emp_name,emp.data$salary)
> print(result)
emp.data.emp_name emp.data.salary
1 Rick 623.30
2 Dan 515.20
3 Michelle 611.00
4 Ryan 729.00
5 Gary 843.25

6. R Operators:-

Arithmetic Operators
Following table shows the arithmetic operators supported by R language.
The operators act on each element of the vector.

Operator Description Example

Live Demo

v <- c( 2,5.5,6)
+ Adds two vectors t <- c(8, 3, 4)
print(v+t)
it produces the following result −
[1] 10.0 8.5 10.0

Live Demo

− Subtracts second vector from the first


v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v-t)
it produces the following result −
[1] -6.0 2.5 2.0

Live Demo

v <- c( 2,5.5,6)
* Multiplies both vectors t <- c(8, 3, 4)
print(v*t)
it produces the following result −
[1] 16.0 16.5 24.0

Live Demo

v <- c( 2,5.5,6)
t <- c(8, 3, 4)
/ Divide the first vector with the second print(v/t)
When we execute the above code, it produces
the following result −
[1] 0.250000 1.833333 1.500000

Live Demo

v <- c( 2,5.5,6)
Give the remainder of the first vector
%% t <- c(8, 3, 4)
with the second print(v%%t)
it produces the following result −
[1] 2.0 2.5 2.0

Live Demo

v <- c( 2,5.5,6)
The result of division of first vector
%/% t <- c(8, 3, 4)
with second (quotient) print(v%/%t)
it produces the following result −
[1] 0 1 1

Live Demo

v <- c( 2,5.5,6)
The first vector raised to the exponent
^ t <- c(8, 3, 4)
of second vector print(v^t)
it produces the following result −
[1] 256.000 166.375 1296.000

Relational Operators
Following table shows the relational operators supported by R language. Each element of the
first vector is compared with the corresponding element of the second vector. The result of
comparison is a Boolean value.

Operator Description Example

Live Demo

Checks if each element of the first vector is v <- c(2,5.5,6,9)


> greater than the corresponding element of the t <- c(8,2.5,14,9)
second vector. print(v>t)
it produces the following result −
[1] FALSE TRUE FALSE FALSE

Live Demo

Checks if each element of the first vector is v <- c(2,5.5,6,9)


< less than the corresponding element of the t <- c(8,2.5,14,9)
second vector. print(v < t)
it produces the following result −
[1] TRUE FALSE TRUE FALSE

Live Demo

Checks if each element of the first vector is v <- c(2,5.5,6,9)


== equal to the corresponding element of the t <- c(8,2.5,14,9)
second vector. print(v == t)
it produces the following result −
[1] FALSE FALSE FALSE TRUE

Live Demo

Checks if each element of the first vector is v <- c(2,5.5,6,9)


<= less than or equal to the corresponding t <- c(8,2.5,14,9)
element of the second vector. print(v<=t)
it produces the following result −
[1] TRUE FALSE TRUE TRUE

Live Demo

Checks if each element of the first vector is v <- c(2,5.5,6,9)


>= greater than or equal to the corresponding t <- c(8,2.5,14,9)
element of the second vector. print(v>=t)
it produces the following result −
[1] FALSE TRUE FALSE TRUE
Live Demo

Checks if each element of the first vector is v <- c(2,5.5,6,9)


!= unequal to the corresponding element of the t <- c(8,2.5,14,9)
second vector. print(v!=t)
it produces the following result −
[1] TRUE TRUE TRUE FALSE

Logical Operators
Following table shows the logical operators supported by R language. It is
applicable only to vectors of type logical, numeric or complex. All
numbers greater than 1 are considered as logical value TRUE.

Each element of the first vector is compared with the corresponding


element of the second vector. The result of comparison is a Boolean
value.

Operator Description Example

Live Demo
It is called Element-wise Logical AND operator.
It combines each element of the first vector v <- c(3,1,TRUE,2+3i)
& with the corresponding element of the second t <- c(4,1,FALSE,2+3i)
vector and gives a output TRUE if both the print(v&t)
elements are TRUE. it produces the following result −
[1] TRUE TRUE FALSE TRUE

Live Demo
It is called Element-wise Logical OR operator. It
combines each element of the first vector with v <- c(3,0,TRUE,2+2i)
| the corresponding element of the second t <- c(4,0,FALSE,2+3i)
vector and gives a output TRUE if one the print(v|t)
elements is TRUE. it produces the following result −
[1] TRUE FALSE TRUE TRUE

Live Demo
It is called Logical NOT operator. Takes each
v <- c(3,0,TRUE,2+2i)
! element of the vector and gives the opposite
print(!v)
logical value.
it produces the following result −
[1] FALSE TRUE FALSE FALSE

The logical operator && and || considers only the first element of the
vectors and give a vector of single element as output.
Operator Description Example

Live Demo

Called Logical AND operator. Takes first element v <- c(3,0,TRUE,2+2i)


&& of both the vectors and gives the TRUE only if t <- c(1,3,TRUE,2+3i)
both are TRUE. print(v&&t)
it produces the following result −
[1] TRUE

Live Demo

Called Logical OR operator. Takes first element of v <- c(0,0,TRUE,2+2i)


|| both the vectors and gives the TRUE if one of t <- c(0,3,TRUE,2+3i)
them is TRUE. print(v||t)
it produces the following result −
[1] FALSE

Assignment Operators
These operators are used to assign values to vectors.

Operator Description Example

Live Demo

v1 <- c(3,1,TRUE,2+3i)
v2 <<- c(3,1,TRUE,2+3i)
<− v3 = c(3,1,TRUE,2+3i)
or print(v1)
= Called Left Assignment print(v2)
or print(v3)
<<− it produces the following result −
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i

Live Demo

-> c(3,1,TRUE,2+3i) -> v1


or Called Right Assignment c(3,1,TRUE,2+3i) ->> v2
->> print(v1)
print(v2)
it produces the following result −
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i

Miscellaneous Operators
These operators are used to for specific purpose and not general
mathematical or logical computation.

Operator Description Example

Colon operator. It Live Demo


creates the series
v <- 2:8
: of numbers in print(v)
sequence for a
vector.
it produces the following result −
[1] 2 3 4 5 6 7 8

Live Demo

v1 <- 8
This operator is v2 <- 12
used to identify if t <- 1:10
%in% an element print(v1 %in% t)
belongs to a print(v2 %in% t)
vector.
it produces the following result −
[1] TRUE
[1] FALSE

Live Demo

M = matrix( c(2,6,5,1,10,4), nrow = 2,ncol = 3,byro


This operator is t = M %*% t(M)
%*%
used to multiply a print(t)
matrix with its it produces the following result −
transpose.
[,1] [,2]
[1,] 65 82
[2,] 82 117
7. R Loops:-
v <- c("Hello","while loop")
cnt <- 2
while (cnt < 7) {
print(v)
cnt = cnt + 1
}
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"

v <- LETTERS[1:4]
for ( i in v) {
print(i)
}
[1] "A"
[1] "B"
[1] "C"
[1] "D"

v <- c("Hello","loop")
cnt <- 2
repeat {
print(v)
cnt <- cnt + 1
if(cnt > 5) {
break
}
}
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"

8. R Conditional Statement

x <- 30L
if(is.integer(x)) {
print("X is an Integer")
}
[1] "X is an Integer"

x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found")
} else {
print("Truth is not found")
}
[1] "Truth is not found"
x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found the first time")
} else if ("truth" %in% x) {
print("truth is found the second time")
} else {
print("No truth found")
}
[1] "truth is found the second time"

9. R Matrices:-
Create a matrix taking a vector of numbers as input.
# Elements are arranged sequentially by row.
M <- matrix(c(3:14), nrow = 4, byrow = TRUE)
print(M)
# Elements are arranged sequentially by column.
N <- matrix(c(3:14), nrow = 4, byrow = FALSE)
print(N)
# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")
P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames,
colnames))
print(P)
[,1] [,2] [,3]
[1,] 3 4 5
[2,] 6 7 8
[3,] 9 10 11
[4,] 12 13 14
[,1] [,2] [,3]
[1,] 3 7 11
[2,] 4 8 12
[3,] 5 9 13
[4,] 6 10 14
col1 col2 col3
row1 3 4 5
row2 6 7 8
row3 9 10 11
row4 12 13 14

Accessing elements from a matrix


# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")
# Create the matrix.
P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames,
colnames))
# Access the element at 3rd column and 1st row.
print(P[1,3])
# Access the element at 2nd column and 4th row.
print(P[4,2])
# Access only the 2nd row.
print(P[2,])
# Access only the 3rd column.
print(P[,3])
[1] 5
[1] 13
col1 col2 col3
6 7 8
row1 row2 row3 row4
5 8 11 14

Matrix Addition & Subtraction


# Create two 2x3 matrices.
matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)
matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
print(matrix2)
# Add the matrices.
result <- matrix1 + matrix2
cat("Result of addition","\n")
print(result)
# Subtract the matrices
result <- matrix1 - matrix2
cat("Result of subtraction","\n")
print(result)
[,1] [,2] [,3]
[1,] 3 -1 2
[2,] 9 4 6
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
Result of addition
[,1] [,2] [,3]
[1,] 8 -1 5
[2,] 11 13 10
Result of subtraction
[,1] [,2] [,3]
[1,] -2 -1 -1
[2,] 7 -5 2

Matrix Multiplication & Division


# Create two 2x3 matrices.
matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)
matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
print(matrix2)
# Multiply the matrices.
result <- matrix1 * matrix2
cat("Result of multiplication","\n")
print(result)
# Divide the matrices
result <- matrix1 / matrix2
cat("Result of division","\n")
print(result)
When we execute the above code, it produces the following result −
[,1] [,2] [,3]
[1,] 3 -1 2
[2,] 9 4 6
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
Result of multiplication
[,1] [,2] [,3]
[1,] 15 0 6
[2,] 18 36 24
Result of division
[,1] [,2] [,3]
[1,] 0.6 -Inf 0.6666667
[2,] 4.5 0.4444444 1.5000000

10.R String:-
a <- "Hello"
b <- 'How'
c <- "are you? "
print(paste(a,b,c))
print(paste(a,b,c, sep = "-"))
print(paste(a,b,c, sep = "", collapse = ""))
When we execute the above code, it produces the following result −
[1] "Hello How are you? "
[1] "Hello-How-are you? "
[1] "HelloHoware you? "

result <- nchar("Count the number of characters")


print(result)
[1] 30

# Changing to Upper case.


result <- toupper("Changing To Upper")
print(result)
# Changing to lower case.
result <- tolower("Changing To Lower")
print(result)

When we execute the above code, it produces the following result −


[1] "CHANGING TO UPPER"
[1] "changing to lower"

# Extract characters from 5th to 7th position.


result <- substring("Extract", 5, 7)
print(result)

When we execute the above code, it produces the following result −


[1] "act"
11.R List:-
# Create a list containing strings, numbers, vectors and a logical
# values.
list_data <- list("Red", "Green", c(21,32,11), TRUE, 51.23, 119.1)
print(list_data)

When we execute the above code, it produces the following result −


[[1]]
[1] "Red"
[[2]]
[1] "Green"
[[3]]
[1] 21 32 11
[[4]]
[1] TRUE
[[5]]
[1] 51.23
[[6]]
[1] 119.1

# Create a list containing a vector, a matrix and a list.


list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
list("green",12.3))
# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")
# Show the list.
print(list_data)

When we execute the above code, it produces the following result −


$`1st_Quarter`
[1] "Jan" "Feb" "Mar"
$A_Matrix
[,1] [,2] [,3]
[1,] 3 5 -2
[2,] 9 1 8
$A_Inner_list
$A_Inner_list[[1]]
[1] "green"
$A_Inner_list[[2]]
[1] 12.3

# Create a list containing a vector, a matrix and a list.


list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
list("green",12.3))
# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")
# Access the first element of the list.
print(list_data[1])
# Access the thrid element. As it is also a list, all its elements will be printed.
print(list_data[3])
# Access the list element using the name of the element.
print(list_data$A_Matrix)

When we execute the above code, it produces the following result −


$`1st_Quarter`
[1] "Jan" "Feb" "Mar"

$A_Inner_list
$A_Inner_list[[1]]
[1] "green"

$A_Inner_list[[2]]
[1] 12.3

[,1] [,2] [,3]


[1,] 3 5 -2
[2,] 9 1 8

# Create two lists.


list1 <- list(1,2,3)
list2 <- list("Sun","Mon","Tue")
# Merge the two lists.
merged.list <- c(list1,list2)
# Print the merged list.
print(merged.list)
When we execute the above code, it produces the following result −
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] "Sun"
[[5]]
[1] "Mon"
[[6]]
[1] "Tue"

12.R Statistical measures:-


# Create a vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5)
# Find Mean.
result.mean <- mean(x)
print(result.mean)

When we execute the above code, it produces the following result −


[1] 8.22

If there are missing values, then the mean function returns NA.
To drop the missing values from the calculation use na.rm = TRUE. which
means remove the NA values.
# Create a vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5,NA)
# Find mean.
result.mean <- mean(x)
print(result.mean)
# Find mean dropping NA values.
result.mean <- mean(x,na.rm = TRUE)
print(result.mean)

When we execute the above code, it produces the following result −


[1] NA
[1] 8.22

# Create the vector.


x <- c(12,7,3,4.2,18,2,54,-21,8,-5)
# Find the median.
median.result <- median(x)
print(median.result)

When we execute the above code, it produces the following result −


[1] 5.6

# Create the function.


getmode <- function(v) {
uniqv <- unique(v)
uniqv[which.max(tabulate(match(v, uniqv)))]
}
# Create the vector with numbers.
v <- c(2,1,2,3,1,2,3,4,1,5,5,3,2,3)
# Calculate the mode using the user function.
result <- getmode(v)
print(result)
# Create the vector with characters.
charv <- c("o","it","the","it","it")
# Calculate the mode using the user function.
result <- getmode(charv)
print(result)

When we execute the above code, it produces the following result −


[1] 2
[1] "it"

13.R Functions:-
Built-in Function
Simple examples of in-built functions are seq(), mean(), max(), sum(x) and
paste(...) etc. They are directly called by user written programs. You can refer
most widely used R functions.
# Create a sequence of numbers from 32 to 44.
print(seq(32,44))
# Find mean of numbers from 25 to 82.
print(mean(25:82))
# Find sum of numbers frm 41 to 68.
print(sum(41:68))
When we execute the above code, it produces the following result −
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526

User-defined Function
We can create user-defined functions in R. They are specific to what a user
wants and once created they can be used like the built-in functions. Below is an
example of how a function is created and used.
# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
Calling a Function
# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Call the function new.function supplying 6 as an argument.
new.function(6)
When we execute the above code, it produces the following result −
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36

Calling a Function without an Argument


# Create a function without an argument.
new.function <- function() {
for(i in 1:5) {
print(i^2)
}
}
# Call the function without supplying an argument.
new.function()
When we execute the above code, it produces the following result −
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25

Calling a Function with Argument Values (by position and by name)


The arguments to a function call can be supplied in the same sequence as
defined in the function or they can be supplied in a different sequence but
assigned to the names of the arguments.
# Create a function with arguments.
new.function <- function(a,b,c) {
result <- a * b + c
print(result)
}
# Call the function by position of arguments.
new.function(5,3,11)
# Call the function by names of the arguments.
new.function(a = 11, b = 5, c = 3)

When we execute the above code, it produces the following result −


[1] 26
[1] 58

Calling a Function with Default Argument


We can define the value of the arguments in the function definition and call the
function without supplying any argument to get the default result. But we can
also call such functions by supplying new values of the argument and get non
default result.
# Create a function with arguments.
new.function <- function(a = 3, b = 6) {
result <- a * b
print(result)
}
# Call the function without giving any argument.
new.function()
# Call the function with giving new values of the argument.
new.function(9,5)
When we execute the above code, it produces the following result −
[1] 18
[1] 45

14.R Charts and Graphs:-


# Create data for the graph.
x <- c(21, 62, 10, 53)
labels <- c("London", "New York", "Singapore", "Mumbai")
# Give the chart file a name.
png(file = "city.png")
# Plot the chart.
pie(x,labels)
# Save the file.
dev.off()

Pie Chart Title and Colors


We can expand the features of the chart by adding more parameters to the
function. We will use parameter main to add a title to the chart and another
parameter is col which will make use of rainbow colour pallet while drawing
the chart. The length of the pallet should be same as the number of values we
have for the chart. Hence we use length(x).
Example
The below script will create and save the pie chart in the current R working
directory.
# Create data for the graph.
x <- c(21, 62, 10, 53)
labels <- c("London", "New York", "Singapore", "Mumbai")
# Give the chart file a name.
png(file = "city_title_colours.jpg")
# Plot the chart with title and rainbow color pallet.
pie(x, labels, main = "City pie chart", col = rainbow(length(x)))
# Save the file.
dev.off()

Slice Percentages and Chart Legend


We can add slice percentage and a chart legend by creating additional chart
variables.
# Create data for the graph.
x <- c(21, 62, 10,53)
labels <- c("London","New York","Singapore","Mumbai")
piepercent<- round(100*x/sum(x), 1)
# Give the chart file a name.
png(file = "city_percentage_legends.jpg")
# Plot the chart.
pie(x, labels = piepercent, main = "City pie chart",col = rainbow(length(x)))
legend("topright", c("London","New York","Singapore","Mumbai"), cex = 0.8,
fill = rainbow(length(x)))
# Save the file.
dev.off()

3D Pie Chart
A pie chart with 3 dimensions can be drawn using additional packages. The
package plotrix has a function called pie3D() that is used for this.
# Get the library.
library(plotrix)
# Create data for the graph.
x <- c(21, 62, 10,53)
lbl <- c("London","New York","Singapore","Mumbai")
# Give the chart file a name.
png(file = "3d_pie_chart.jpg")
# Plot the chart.
pie3D(x,labels = lbl,explode = 0.1, main = "Pie Chart of Countries ")
# Save the file.
dev.off()

# Create the data for the chart


H <- c(7,12,28,3,41)
M <- c("Mar","Apr","May","Jun","Jul")
# Give the chart file a name
png(file = "barchart_months_revenue.png")
# Plot the bar chart
barplot(H,names.arg=M,xlab="Month",ylab="Revenue",col="blue",
main="Revenue chart",border="red")
# Save the file
dev.off()
Group Bar Chart and Stacked Bar Chart
We can create bar chart with groups of bars and stacks in each bar by using a
matrix as input values.
More than two variables are represented as a matrix which is used to create
the group bar chart and stacked bar chart.
# Create the input vectors.
colors = c("green","orange","brown")
months <- c("Mar","Apr","May","Jun","Jul")
regions <- c("East","West","North")
# Create the matrix of the values.
Values <- matrix(c(2,9,3,11,9,4,8,7,3,12,5,2,8,10,11), nrow = 3, ncol = 5, byrow
= TRUE)
# Give the chart file a name
png(file = "barchart_stacked.png")
# Create the bar chart
barplot(Values, main = "total revenue", names.arg = months, xlab = "month",
ylab = "revenue", col = colors)
# Add the legend to the chart
legend("topleft", regions, cex = 1.3, fill = colors)
# Save the file
dev.off()

# Create data for the graph.


v <- c(9,13,21,8,36,22,12,41,31,33,19)
# Give the chart file a name.
png(file = "histogram.png")
# Create the histogram.
hist(v,xlab = "Weight",col = "yellow",border = "blue")
# Save the file.
dev.off()
# Create the data for the chart.
v <- c(7,12,28,3,41)
# Give the chart file a name.
png(file = "line_chart_label_colored.jpg")
# Plot the bar chart.
plot(v,type = "o", col = "red", xlab = "Month", ylab = "Rain fall",
main = "Rain fall chart")
# Save the file.
dev.off()

More than one line can be drawn on the same chart by using
the lines()function.
After the first line is plotted, the lines() function can use an additional vector as
input to draw the second line in the chart,
# Create the data for the chart.
v <- c(7,12,28,3,41)
t <- c(14,7,6,19,3)
# Give the chart file a name.
png(file = "line_chart_2_lines.jpg")
# Plot the bar chart.
plot(v,type = "o",col = "red", xlab = "Month", ylab = "Rain fall",
main = "Rain fall chart")
lines(t, type = "o", col = "blue")
# Save the file.
dev.off()

15.R Reading File:-


data <- read.csv("input.csv")
print(data)
When we execute the above code, it produces the following result −
id, name, salary, start_date, dept
1 1 Rick 623.30 2012-01-01 IT
2 2 Dan 515.20 2013-09-23 Operations
3 3 Michelle 611.00 2014-11-15 IT
4 4 Ryan 729.00 2014-05-11 HR
5 NA Gary 843.25 2015-03-27 Finance
6 6 Nina 578.00 2013-05-21 IT
7 7 Simon 632.80 2013-07-30 Operations
8 8 Guru 722.50 2014-06-17 Finance

data <- read.csv("input.csv")


print(is.data.frame(data))
print(ncol(data))
print(nrow(data))
When we execute the above code, it produces the following result −
[1] TRUE
[1] 5
[1] 8

# Create a data frame.


data <- read.csv("input.csv")
# Get the max salary from data frame.
sal <- max(data$salary)
print(sal)
When we execute the above code, it produces the following result −
[1] 843.25

Get the details of the person with max salary


We can fetch rows meeting specific filter criteria similar to a SQL where clause.
# Create a data frame.
data <- read.csv("input.csv")
# Get the max salary from data frame.
sal <- max(data$salary)
# Get the person detail having max salary.
retval <- subset(data, salary == max(salary))
print(retval)

When we execute the above code, it produces the following result −


id name salary start_date dept
5 NA Gary 843.25 2015-03-27 Finance

Get all the people working in IT department


# Create a data frame.
data <- read.csv("input.csv")
retval <- subset( data, dept == "IT")
print(retval)
When we execute the above code, it produces the following result −
id name salary start_date dept
1 1 Rick 623.3 2012-01-01 IT
3 3 Michelle 611.0 2014-11-15 IT
6 6 Nina 578.0 2013-05-21 IT
Get the persons in IT department whose salary is greater than 600
# Create a data frame.
data <- read.csv("input.csv")
info <- subset(data, salary > 600 & dept == "IT")
print(info)
When we execute the above code, it produces the following result −
id name salary start_date dept
1 1 Rick 623.3 2012-01-01 IT
3 3 Michelle 611.0 2014-11-15 IT
# Read the first worksheet in the file input.xlsx.
data <- read.xlsx("input.xlsx", sheetIndex = 1)
print(data)

When we execute the above code, it produces the following result −


id, name, salary, start_date, dept
1 1 Rick 623.30 2012-01-01 IT
2 2 Dan 515.20 2013-09-23 Operations
3 3 Michelle 611.00 2014-11-15 IT
4 4 Ryan 729.00 2014-05-11 HR
5 NA Gary 843.25 2015-03-27 Finance
6 6 Nina 578.00 2013-05-21 IT
7 7 Simon 632.80 2013-07-30 Operations
8 8 Guru 722.50 2014-06-17 Finance

You might also like