Me-I 2022 - ML Lab
Me-I 2022 - ML Lab
Me-I 2022 - ML Lab
:1 CASE STUDY ON R
Date :
Introduction
R is a programming language and software environment for statistical analysis,
graphics representation and reporting.
R was created by Ross Ihaka and Robert Gentleman at the University of Auckland,
New Zealand, and is currently developed by the R Development Core Team.
R is freely available under the GNU General Public License, and pre-compiled binary
versions are provided for various operating systems like Linux, Windows and Mac.
This programming language was named R, based on the first letter of first name of the
two R authors (Robert Gentleman and Ross Ihaka), and partly a play on the name of
the Bell Labs Language S.
Features of R
R is a well-developed, simple and effective programming language which includes
conditionals, loops, user defined recursive functions and input and output facilities.
R has an effective data handling and storage facility,
R provides a suite of operators for calculations on arrays, lists, vectors and matrices.
R provides a large, coherent and integrated collection of tools for data analysis.
R provides graphical facilities for data analysis and display either directly at the
computer or printing at the papers.
R-objects
There are many types of R-objects. The frequently used ones are −
Vectors
Lists
Matrices
Arrays
Factors
Data Frames
Types of Operators
We have the following types of operators in R programming −
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Miscellaneous Operators
1 if statement
An if statement consists of a Boolean expression followed by one or more statements.
2 if...else statement
An if statement can be followed by an optional else statement, which executes when
the Boolean expression is false.
3 switch statement
A switch statement allows a variable to be tested for equality against a list of values.
1 repeat loop
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
2 while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
3 for loop
Like a while statement, except that it tests the condition at the end of the loop body.
1 break statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
2 Next statement
The next statement simulates the behavior of R switch.
Function Components
The different parts of a function are −
Function Name − This is the actual name of the function. It is stored in R
environment as an object with this name.
Arguments − An argument is a placeholder. When a function is invoked, you pass a
value to the argument. Arguments are optional; that is, a function may contain no
arguments. Also arguments can have default values.
Function Body − The function body contains a collection of statements that defines
what the function does.
Return Value − The return value of a function is the last expression in the function
body to be evaluated.
Ex.No.2 IMPLEMENTATION OF R PROGRAMS USING VECTORS AND LISTS
Date :
Aim
To write R programming for implementation of Vectors and Lists
Algorithm
Step 1: Start the Program.
Step 2: For Single element Vector print the values based on datatypes like character, double,
integer, Logical, complex and raw.
Step 3: Using seq operator print the elements according to sequence given from 5.6 to 9
Step 4: Print the vector elements by using position, logical indexing.
Step 5: Create two vectors and perform arithmetic operations for given vectors.
Step 6: Create a list containing values containing strings,integers,logical values.
Step 7: Manipulate list elements using add,delete and update operations.
Step 8: Merge all the list as one list using one list function and convert list to vector using
unlist() function.
Step 6: Stop the program.
Program
Using Single Element Vector
# Atomic vector of type character.
print("abc");
# Atomic vector of type double.
print(12.5)
# Atomic vector of type integer.
print(63L)
# Atomic vector of type logical.
print(TRUE)
# Atomic vector of type complex.
print(2+3i)
Using sequence (Seq.) operator
# Create vector with elements from 5 to 9 incrementing by 0.4.
print(seq(5, 9, by = 0.4))
Using the c() function
# The logical and numeric values are converted to characters.
s <- c('apple','red',5,TRUE)
print(s)
Output
[1] "abc"
[1] 12.5
[1] 63
[1] TRUE
[1] 2+3i
[1] 5.0 5.4 5.8 6.2 6.6 7.0 7.4 7.8 8.2 8.6 9.0
List
list_data <- list("Red", "Green", c(21,32,11), TRUE, 51.23, 119.1)
print(list_data)
# Create lists.
list1 <- list(1:5)
print(list1)
list2 <-list(10:14)
print(list2)
# Convert the lists to vectors.
v1 <- unlist(list1)
v2 <- unlist(list2)
print(v1)
print(v2)
# Now add the vectors
result <- v1+v2
print(result)
Output:
[[1]]
[1] "Red"
[[2]]
[1] "Green"
[[3]]
[1] 21 32 11
[[4]]
[1] TRUE
[[5]]
[1] 51.23
[[6]]
[1] 119.1
[[1]]
[1] "New element"
$<NA>
NULL
$`A Inner list`
[1] "updated element"
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] "Sun"
[[5]]
[1] "Mon"
[[6]]
[1] "Tue"
[[1]]
[1] 1 2 3 4 5
[[1]]
[1] 10 11 12 13 14
[1] 1 2 3 4 5
[1] 10 11 12 13 14
[1] 11 13 15 17 19
Result
Thus R program for vectors and Lists were implemented and executed successfully.
Ex.No. 3 IMPLEMENTATION OF R PROGRAMS USING ARRAYS
Date :
Aim:
To write a R Program to implement Arrays
Algorithm:
Step 1: Start the Program
Step 2: Declare two vectors and create an array of 3 dimenional matrices
Step 3: Create vectors of different length and convert to array
Step 4: Perform arithmetic operation on matrices created from array
Step 5: Use apply() function to calculate sum of rows across all matrices
Step 5: Stop the Program
Program:
# Create two vectors of different lengths.
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)
column.names <- c("COL1","COL2","COL3")
row.names <- c("ROW1","ROW2","ROW3")
matrix.names <- c("Matrix1","Matrix2")
# Take these vectors as input to the array.
result <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names,column.names,
matrix.names))
print(result)
Output:
Matrix1
COL1 COL2 COL3
ROW1 5 10 13
ROW2 9 11 14
ROW3 3 12 15
, , Matrix2
COL1 COL2 COL3
ROW1 5 10 13
ROW2 9 11 14
ROW3 3 12 15
,,1
Result:
Thus R program for arrays was implemented and executed successfully.
Ex.No. 4 IMPLEMENTATION OF R PROGRAMS USING FACTORS
Date :
Aim
To write a R program to implement factor functions
Algorithm
Step 1: Start the Program
Step 2: Declare the vector input variables and initialize the values
Step 3: Apply the factor function to print the data
Step 4: Create vectors for data frame and print the specific values given in data frame
Step 5: Check whether the input is factor and return the values
Step 6: Apply the factor function to change the order of levels in factor
Step 7: Initialize integer values and print the number of levels for the input using gl() function
Step 8: Stop the Program
Program:
# Create a vector as input.
data <-
c("East","West","East","North","North","East","West","West","West","East","North")
print(data)
print(is.factor(data))
# Apply the factor function.
factor_data <- factor(data)
print(factor_data)
print(is.factor(factor_data))
Output
[1] "East" "West" "East" "North" "North" "East" "West" "West" "West" "East" "North"
[1] FALSE
[1] East West East North North East West West West East North
Levels: East North West
[1] TRUE
height weight gender
1 132 48 male
2 151 49 male
3 162 66 female
4 139 53 female
5 166 67 male
6 147 52 female
7 122 40 male
[1] TRUE
[1] male male female female male female male
Levels: female male
[1] East West East North North East West West West East North
Levels: East North West
[1] East West East North North East West West West East North
Levels: East West North
Result
Thus R program for factors function was implemented and executed successfully.
Ex.No. 5 IMPLEMENTATION OF R PROGRAMS USING DATA FRAMES
Date :
Aim
To write R program to implement Data Frames.
Algorithm
Step 1: Start the program.
Step 2: Create the data frame.
Step 3: The structure of the data frame can be created by using str() function.
Step 4: Get the statistical summary and nature of the data can be obtained by applying
Summary () function.
Step 5: Print the summary.
Step 6: Extract specific column from a data frame using column name and extract specific
row from a data frame using row name.
Step 7: A data frame can be expanded by adding columns and rows.
Step 8: Two data frames can be created and blind the two data frames.
Step 9: Stop the program.
Program:
# 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)
Output:
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
Output:
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 Data from Data Frame
Extract specific column from a data frame using column name.
# 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
)
# Extract Specific columns.
result <- data.frame(emp.data$emp_name,emp.data$salary)
print(result)
Output:
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
Extract the first two rows and then all columns
Output
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 5 Gary 843.25 2015-03-27 Finance
6 6 Rasmi 578.00 2013-05-21 IT
7 7 Pranab 722.50 2013-07-30 Operations
8 8 Tusar 632.80 2014-06-17 Fianance
Result
Thus R program for Looping statement was implemented and executed successfully.
Ex. No. 6 IMPLEMENTATION OF R PROGRAMS USING DECISION
Date: MAKING STATEMENTS
Aim
To write R program to implement Decision Making Statements.
Algorithm
Step 1: Start the program.
Step 2: Declare the variables.
Step 3: if statement: Check the condition. If the condition is true execute the code otherwise
exit from the program.
Step 4: if..else statement: Check the condition. If the condition is true execute the code
otherwise execute the else condition code.
Step 5: if..else Ladder(if..else..if): Check the condition1. If the condition1 is true execute
the code and return. Or else check the condition2 if the condition2 is true execute the
code otherwise execute the condition3 code and exit.
Step 6: nested if..else statement: Check the if condition, then child if condition is validated
or else statement is executed, If parent if condition is false then else block is
executed.
Step 7: Execute the output.
Step 8: Stop the program.
Program:
if statement :
Syntax Program
if(condition is true) x <-24L
{ y <- "shubham"
execute this statement if(is.integer(x))
} {
print("x is an Integer")
}
Result
Thus R program for decision making statement was implemented successfully.
Ex No.:7 IMPLEMENTATION OF R PROGRAMS USING
Date : LOOPING STATEMENTS
Aim:
To write R program to implement Looping Statements.
Algorithm:
Step 1: Start the program.
Step 2: Declare the variables.
Step 3: for loop: In this loop the test condition is tested first, then the body of the loop is
executed, it would not be executed if the test condition is false.
Step 4: while loop: While loop checks for the condition to be true or false n+1 times rather
than n times.
Step 5: repeat loop: It executes the same code again and again until a break statement is
Found.Repeat loop, unlike other loops executes, fora break statement that executes
if a condition within the loop body results to be true.
Step 6: Execute the output.
Step 7: Stop the program.
Program:
for loop:
Syntax Program
for (var in vector)
for (i in 1: 4)
{
{
statement(s)
print(i ^ 2)
}
}
Output:
1
4
9
16
While loop:
Syntax Program
while (test_expression) result <- c("Hello World")
{ i <- 1
statement # test expression
while (i < 6)
update_expression
{
} print(result)
# update expression
i=i+1
}
Output: 1
2
3
4
5
Result
Thus R program for Looping statement was implemented successfully.
Ex No.:8 IMPLEMENTATION OF R PROGRAMS USING FUNCTION
DATE : WITH ARGUMENT.
Aim:
Write a R programming for implementation of function with argument.
Algorithm:
Step 1 : Start the program.
Step 2 : Initialize and declare the variables.
Step 3 : Using the function call with argument ,check the condition,
Step 4 :Execute the output .
Step 5 : Stop the program.
Program:
# Create a function with arguments.
new.function <- function(a,b,c)
{
result <- a * b + c
print(result)
}
Output:
26
58
Result:
Thus the R programming of function using with argument was implemented and
executed successfully.
Ex No.:9 IMPLEMENTATION OF R PROGRAMS USING FUNCTION
DATE : WITHOUT ARGUMENT
Aim:
Write a R program for implementation of function without argument.
Algorithm:
Step 1 : Start the program.
Step 2 : Initialize and declare the variables.
Step 3 : Using the function call without argument ,check the for condition.
Step 4 : Execute the output .
Step 5 : Stop the program.
Program:
# 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()
Output:
1
4
9
16
25
Result:
Thus the R programming of function using with argument was implemented and
executed successfully.
Ex no.:10 IMPLEMENTATION OF R CHARTS & GRAPHS
Date :
Aim:
Write a R program for implementations of R charts and Graphs.
Algorithm:
Step 1 : Start the program.
Step 2 : Initialize and declare the variables and labels.
Step 3 : Create data for the graph
Step 4 : Give the chart file a name.
Step 5 : Save the file.
Step 6 : Execute the program.
Step 7 : Stop the program.
Program:
Pie Chart
# 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.jpg")
# Plot the chart.
pie(x,labels)
# Save the file.
dev.off()
Output:
Bar Chart
# Create the data for the chart
H <- c(7,12,28,3,41)
# Give the chart file a name
png(file = "barchart.png")
# Plot the bar chart
barplot(H)
# Save the file
dev.off()
Output:
Box Plot
# Give the chart file a name.
png(file = "boxplot.png")
# Plot the chart.
boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders",
ylab = "Miles Per Gallon", main = "Mileage Data")
# Save the file.
dev.off()
Output:
Histograms
# 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()
Output:
R Graphs
Line Graphs
# Create the data for the chart.
v <- c(7,12,28,3,41)
# Give the chart file a name.
png(file = "line_chart.jpg")
# Plot the bar chart.
plot(v,type = "o")
# Save the file.
dev.off()
Output:
Scatter Plot
# Get the input values.
input <- mtcars[,c('wt','mpg')]
# Give the chart file a name.
png(file = "scatterplot.png")
# Plot the chart for cars with weight between 2.5 to 5 and mileage between 15 and 30.
plot(x = input$wt,y = input$mpg,
xlab = "Weight",
ylab = "Milage",
xlim = c(2.5,5),
ylim = c(15,30),
main = "Weight vs Milage")
# Save the file.
dev.off()
output:
Result:
Thus the R program of R charts and Graphs was implemented and executed
successfully.