R Programming Laboratory Assignments
R Programming Laboratory Assignments
Programme Name: -
Semester / Year:-
Course Code: -
Course Name: -
Roll No :-
Registration No :-
Student Code : -
INDEX
[Link]. Topic Page No. Exp. Date Submission Signature Remarks
date
1 Assignment -1
7-8 30/01/2025
Create a numeric vector of 10
elements and perform.
2 Assignment -2
Write an R program to: 9-11 20/02/2025
Create a 3x3 matrix with numbers from 1
to 9 and perform.
Create a 2x2x3 array with numbers from
1 to 12, name its rows,
columns, and dimensions, and access
specific elements.
3 Assignment – 3
Write an R program to: 12-13 27/02/2025
1. Check if a number entered by the user is
positive, negative or zero using if-else.
2. Use a for loop to print the first 10 natural
numbers.
3. Use a while loop to calculate the factorial of
a given number.
4. Demonstrate the use of break and next
statements in a repeat loop.
4 Assignment – 4
a. Create a vector of numbers from 1 14-16 27/02/2025
to 10.
2|Page
6 Assignment – 6
Write an R script to: 21-27 27/03/2025
3|Page
b) Calculate the square root, factorial, and
exponential of a number.
c) Compute the sine, cosine, and tangent of
an angle in both degrees and radians.
[Link] the following
mathematical expression in R:
4|Page
13 Assignment – 13
[Link] a pie chart to represent the 50-53 17/04/25
proportion of categories in a
dataset.
Use the ggplot2 package to create the
following:
a) A scatter plot with a regression line.
b) A grouped bar chart for categorical
data.
15 Assignment – 15
[Link] a correlation matrix for a dataset 55-57 01/05/25
and visualize it using a heatmap.
16 Assignment – 16
[Link] the regression model output 58-59 15/05/25
and interpret the following:
a) R-squared value.
b) Coefficients of the regression
equation.
c) p-values of the model terms.
17 Assignment – 17
[Link] a regression model using a 60-62 15/05/25
training dataset. Use it to predict
outcomes for a test dataset.
5|Page
19 Assignment – 19
[Link] the Boston dataset from the MASS 68-69 22/05/25
package to predict medv(median home
value) based on lstat (percentage of
lower status population). Evaluate the
residuals and R-squared value.
20 Assignment – 20
Fit a polynomial regression model to 70 22/05/25
predict mpg based on wt and visualize
the results with a smooth curve.
21 Assignment – 21
Use the rpart package to build a decision 71 22/05/25
tree classifier for the iris
dataset, predicting the species of flowers.
22 Assignment – 22
Use the class package to build a KNN 72-74 22/05/25
classifier for the iris dataset.
Experiment with different values of k.
23 Assignment – 23
Compare classification models (e.g., 75-78 22/05/25
logistic regression, decision tree,
SVM) on the iris dataset using metrics
such as accuracy, precision, recall,
and F1 score.
6|Page
Assignment-1
Code-
num_vector <- c(5, 12, 8, 20, 15, 25, 30, 10, 18, 22)
vector_sum <- sum(num_vector)
vector_mean <- mean(num_vector)
third_element <- num_vector[3]
fifth_element <- num_vector[5]
cat("Sum of vector:", vector_sum, "\n")
cat("Mean of vector:", vector_mean, "\n")
cat("3rd Element:", third_element, "\n")
cat("5th Element:", fifth_element, "\n")
Ouput-
Code-
Age = 20,
print(my_list)
7|Page
Output-
$Name
$Age
[1] 20
$Favorite_Numbers
[1] 10 11 19 28 35
$Favorite_Color
[1] "Blue"
8|Page
Assignment-2
Code-
my_matrix <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE)
transposed_matrix <- t(my_matrix)
row_sums <- rowSums(my_matrix)
col_sums <- colSums(my_matrix)
cat("Original Matrix:\n")
print(my_matrix)
cat("\nTransposed Matrix:\n")
print(transposed_matrix)
cat("\nRow-wise Sums:\n")
print(row_sums)
cat("\nColumn-wise Sums:\n")
print(col_sums)
Output-
Original Matrix:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
9|Page
Transposed Matrix:
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
Row-wise Sums:
[1] 6 15 24
Column-wise Sums:
[1] 12 15 18
Create a 2x2x3 array with numbers from 1 to 12, name its rows, columns, and dimensions,
and access specific elements.
Code-
my_array <- array(1:12, dim = c(2, 2, 3))
dimnames(my_array) <- list(
Rows = c("Row1", "Row2"),
Columns = c("Col1", "Col2"),
Dimensions = c("Matrix1", "Matrix2", "Matrix3")
)
cat("Array with named dimensions:\n")
print(my_array)
element_1 <- my_array["Row1", "Col1", "Matrix1"] # Access element in first matrix
element_2 <- my_array["Row2", "Col2", "Matrix2"] # Access element in second matrix
cat("\nAccessed Elements:\n")
cat("Element at (Row1, Col1, Matrix1):", element_1, "\n")
cat("Element at (Row2, Col2, Matrix2):", element_2, "\n")
10 | P a g e
Output-
Col1 Col2
Row1 1 3
Row2 2 4
, , Dimensions = Matrix2
Col1 Col2
Row1 5 7
Row2 6 8
, , Dimensions = Matrix3
Col1 Col2
Row1 9 11
Row2 10 12
Accessed Elements:
Element at (Row1, Col1, Matrix1): 1
Element at (Row2, Col2, Matrix2): 8
11 | P a g e
Assignment-3
Code-
a <- 10
if(a>1){
print("the number is positive")
}else if(a<1){
print("the number is negetive")
}else{
print("the number is one")
}
Output-
the number is positive
for (i in 1:10) {
cat(i, "\n")
}
Output-
1
2
3
4
5
6
7
8
9
10
12 | P a g e
Code-
num <- 5
fact <- 1
i <- 1
while(i<=num){
fact<-fact*i
i<-i+1
}
print(fact)
Output-
[1] 120
Code-
i <- 1
repeat{
if(i%%2==0){
i <- i+1
next
}
print(i)
if(i==9){
break
}
i <- i+1
}
Output-
[1] 1
[1] 3
[1] 5
[1] 7
[1] 9
13 | P a g e
Assignment-4
[Link] a vector of numbers from 1 to 10.
1. Calculate the mean(), sum(), min(), and max() of the vector.
2. Generate a sequence from 5 to 50 with a step of 5 using seq().
3. Concatenate the numbers and print them as a single string using paste().
Code-
numbers <- 1:10
Output-
Mean: 5.5
Sum: 55
Min: 1
14 | P a g e
Max: 10
Sequence: 5 10 15 20 25 30 35 40 45 50
Code-
text <- "Brainware University"
substring_text <- substr(text, 1, 9)
split_text <- strsplit(text, " ")
uppercase_text <- toupper(text)
lowercase_text <- tolower(text)
print(paste("Extracted Substring:", substring_text))
print("Split Words:")
print(split_text)
print(paste("Uppercase:", uppercase_text))
print(paste("Lowercase:", lowercase_text))
Output-
[1] "Extracted Substring: Brainware"
[1] "Split Words:"
[[1]]
[1] "Brainware" "University"
15 | P a g e
C. create a vector using seq() from 1 to 20. Write a program to:
1. Repeat the vector three times using rep().
2. Access the first 5 elements of the vector.
3. Demonstrate vector recycling by adding this vector to another vector of length 5.
Code-
vec <- seq(1, 20)
Output-
Repeated Vector:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
First 5 Elements:
12345
Vector Recycling Result:
11 22 33 44 55 16 27 38 49 60 21 32 43 54 65 26 37 48 59 70
16 | P a g e
Assignment-5
Write a script to process the text "R Programming is Fun and
Challenging".
1. Extract every second word from the sentence.
2. Count the number of occurrences of vowels (a, e, i, o, u) in the string.
3. Replace the word "Challenging" with "Exciting".
Code-
text <- "R Programming is Fun and Challenging"
words <- unlist(strsplit(text, " "))
second_word <- words[seq(2, length(words), by = 2)]
extracted_words <- paste(second_words,collopse = " ")
count_vowels <- function(text){
sum(length(gregexpr("[aeiouAEIOU]",text,perl = TRUE)))
}
updated_text <- gsub("\\behallenging\\b","Exciting",text)
cat("Extracted words:",extracted_words,"\n")
cat("Vowel Count:",vowel_count,"\n")
cat("Extracted words:",updated_text,"\n")
Output-
Extracted words: Programming Fun Challenging
Vowel Count: 9
Extracted words: R Programming is Fun and Challenging
17 | P a g e
• Create a nested list containing:
1. A data frame with student names, marks, and grades.
2. A vector with the total marks for each student.
3. A list of factors indicating the performance category ("Excellent", "Good", "Average").
Code-
students_df <- [Link](
Name = c("Rohit", "Srijit", "Samrat", "Rounak"),
Marks = c(95, 78, 60, 88),
Grade = c("A", "B", "C", "A")
)
total_marks <- students_df$Marks
performance_categories <- factor(
c("Excellent", "Good", "Average", "Excellent"),
levels = c("Average", "Good", "Excellent")
)
nested_list <- list(
Student_Data = students_df,
Total_Marks = total_marks,
Performance_Category = performance_categories
)
print(nested_list)
Output-
$Student_Data
Name Marks Grade
1 Rohit 95 A
2 Srijit 78 B
3 Samrat 60 C
4 Rounak 88 A
18 | P a g e
$Total_Marks
[1] 95 78 60 88
$Performance_Category
[1] Excellent Good Average Excellent
Levels: Average Good Excellent
Code-
19 | P a g e
new_student <- [Link](Name = "Suvendu", Marks = 90, Grade = "A")
nested_list$Student_Data <- rbind(nested_list$Student_Data, new_student)
nested_list$Total_Marks <- nested_list$Student_Data$Marks
new_performance <- factor("Excellent", levels = c("Average", "Good", "Excellent"))
nested_list$Performance_Category <- c(nested_list$Performance_Category, new_performance)
excellent_students <- nested_list$Student_Data[nested_list$Performance_Category == "Excellent", ]
print(nested_list)
print("Students with Excellent Performance:")
print(excellent_students)
Output-
$Student_Data
Name Marks Grade
1 Rohit 95 A
2 Srijit 78 B
3 Samrat 60 C
4 Rounak 88 A
5 Suvendu 90 A
$Total_Marks
[1] 95 78 60 88 90
$Performance_Category
[1] Excellent Good Average Excellent Excellent
Levels: Average Good Excellent
20 | P a g e
Assignment-6
Write an R script to:
1. Create a data frame with the following columns:
Name, Age, Marks.
Code-
students <- [Link](
Name = c("Samrat", "Srijit", "Rohit"),
Age = c(20, 22, 21),
Score = c(85, 90, 88),
stringsAsFactors = FALSE
)
print(students)
Output-
Name Age Score
1 Samrat 20 85
2 Srijit 22 90
3 Rohit 21 88
Code-
students <- [Link](
Name = c("Samrat", "Srijit", "Rohit"),
Age = c(20, 22, 21),
Score = c(85, 90, 88),
stringsAsFactors = FALSE
)
21 | P a g e
str(students)
Output-
'[Link]': 3 obs. of 3 variables:
$ Name : chr "Samrat" "Srijit" "Rohit"
$ Age : num 20 22 21
$ Score: num 85 90 88
Output-
[1] 3 3
[1] 3
[1] 3
22 | P a g e
4. View the first and last few rows using head() and tail()
Code-
students <- [Link](
Name = c("Samrat", "Srijit", "Rohit"),
Age = c(20, 22, 21),
Score = c(85, 90, 88),
stringsAsFactors = FALSE
)
head(students)
tail(students)
Output-
Name Age Score
1 Samrat 20 85
2 Srijit 22 90
3 Rohit 21 88
23 | P a g e
)
print(df)
Output-
int(df)
Name Age Score
1 Samrat 25 85
2 Srijit 30 90
3 Rohit 22 78
4 Rounak 35 88
5 Suvendu 28 92
Code-
df <- [Link](
Name = c("Samrat", "Srijit", "Rohit", "Rounak", "Suvendu"),
Age = c(25, 30, 22, 35, 28),
Score = c(85, 90, 78, 88, 92)
)
df$Name # or df[, "Name"]
df[1, ]
df[1:2, c("Age", "Score")]
Output-
[1] "Samrat" "Srijit" "Rohit" "Rounak" "Suvendu"
Name Age Score
24 | P a g e
1 Samrat 25 85
Age Score
1 25 85
2 30 90
Code-
df <- [Link](
Name = c("Samrat", "Srijit", "Rohit", "Rounak", "Suvendu"),
Age = c(25, 30, 22, 35, 28),
Score = c(85, 90, 78, 88, 92)
)
dim(df)
nrow(df)
ncol(df)
str(df)
summary(df)
25 | P a g e
names(df)
head(df)
tail(df)
Output-
[1] 5 3
[1] 5
[1] 3
26 | P a g e
5 Suvendu 28 92
27 | P a g e
Assignment-7
• Add a new column, "Grade", to your data frame with values
"A", "B", "A".
Code-
df <- [Link](
Name = c("Samrat", "Srijit", "Rohit", "Rounak", "Suvendu"),
Age = c(25, 30, 22, 35, 28),
Score = c(85, 90, 78, 88, 92)
)
df$Grade <- c("A", "B", "A", "B", "A")
print(df)
Output-
Name Age Score Grade
1 Samrat 25 85 A
2 Srijit 30 90 B
3 Rohit 22 78 A
4 Rounak 35 88 B
5 Suvendu 28 92 A
• Add a new row to your data frame with the details of another student.
Code-
df <- [Link](
Name = c("Samrat", "Srijit", "Rohit", "Rounak", "Suvendu"),
Age = c(25, 30, 22, 35, 28),
Score = c(85, 90, 78, 88, 92)
)
df$Grade <- c("A", "B", "A", "B", "A")
new_student <- [Link](Name = "Shivam", Age = 27, Score = 80, Grade = "B")
28 | P a g e
df <- rbind(df, new_student)
print(df)
Output-
Name Age Score Grade
1 Samrat 25 85 A
2 Srijit 30 90 B
3 Rohit 22 78 A
4 Rounak 35 88 B
5 Suvendu 28 92 A
6 Shivam 27 80 B
Code-
df1 <- [Link](
Name = c("Samrat", "Srijit"),
Age = c(25, 30),
Score = c(85, 90),
Grade = c("A", "B")
)
29 | P a g e
Output-
Name Age Score Grade
1 Samrat 25 85 A
2 Srijit 30 90 B
3 Rohit 22 78 A
4 Rounak 35 88 B
Code-
df <- [Link](
Name = c("Samrat", "Srijit", "Rounak", "Rohit"),
Age = c(25, 30, 22, 35),
Score = c(85, 90, 78, 88),
Grade = c("A", "B", "A", "B")
)
hobbies <- c("Reading", "Cycling", "Painting", "Gaming")
df <- cbind(df, Hobbies = hobbies)
print(df)
Output-
Name Age Score Grade Hobbies
1 Samrat 25 85 A Reading
2 Srijit 30 90 B Cycling
3 Rounak 22 78 A Painting
4 Rohit 35 88 B Gaming
30 | P a g e
Merge two data frames using a common column ("ID") and
display the result.
Code-
df1 <- [Link](
ID = c(1, 2, 3),
Name = c("Samrat", "Srijit", "Rounak"),
Age = c(25, 30, 22)
)
df2 <- [Link](
ID = c(1, 2, 3),
Score = c(85, 90, 78),
Grade = c("A", "B", "A")
)
Output-
ID Name Age Score Grade
1 1 Samrat 25 85 A
2 2 Srijit 30 90 B
3 3 Rounak 22 78 A
31 | P a g e
Assignment-8
Code-
a <- 10
b <- 5
sum_result <- a + b
print(paste("Addition:", sum_result))
sub_result <- a - b
print(paste("Subtraction:", sub_result))
mul_result <- a * b
print(paste("Multiplication:", mul_result))
div_result <- a / b
print(paste("Division:", div_result))
Output-
[1] "Addition: 15"
[1] "Subtraction: 5"
[1] "Multiplication: 50"
[1] "Division: 2"
32 | P a g e
exp_result <- exp(num)
cat("Square root of", num, ":", sqrt_result, "\n")
cat("Factorial of", num, ":", factorial_result, "\n")
cat("Exponential of", num, "(e^num):", exp_result, "\n")
Output-
Square root of 5 : 2.236068
Factorial of 5 : 120
Exponential of 5 (e^num) : 148.4132
c) Compute the sine, cosine, and tangent of an angle in both degrees and
radians.
Code-
angle_deg <- 45
angle_rad <- angle_deg * pi / 180
sin_rad <- sin(angle_rad)
cos_rad <- cos(angle_rad)
tan_rad <- tan(angle_rad)
sin_deg <- sin(angle_deg * pi / 180)
cos_deg <- cos(angle_deg * pi / 180)
tan_deg <- tan(angle_deg * pi / 180)
cat("Angle:", angle_deg, "degrees /", angle_rad, "radians\n")
cat("Sine (rad):", sin_rad, "\n")
cat("Cosine (rad):", cos_rad, "\n")
cat("Tangent (rad):", tan_rad, "\n")
Output-
Angle: 45 degrees / 0.7853982 radians
Sine (rad): 0.7071068
Cosine (rad): 0.7071068
Tangent (rad): 1
33 | P a g e
[Link] the following mathematical expression in R:
Code-
x_values <- 1:10
results <- (3*x_values^2 + 5*x_values + 2) / (x_values^2 + 1)
print(results)
Output-
[1] 5.000000 4.800000 4.400000 4.117647 3.923077 3.783784 3.680000 3.600000 3.536585 3.485149
Code-
numbers <- c(3, 7, 2, 9)
sum_result <- sum(numbers)
product_result <- prod(numbers)
cat("Sum of elements:", sum_result, "\n")
cat("Product of elements:", product_result, "\n")
Output-
Sum of elements: 21
Product of elements: 378
34 | P a g e
b) Mean, median, and standard deviation.
Code-
numbers <- c(10, 20, 30, 40, 50)
mean_result <- mean(numbers)
median_result <- median(numbers)
sd_result <- sd(numbers)
cat("Mean:", mean_result, "\n")
cat("Median:", median_result, "\n")
cat("Standard Deviation:", sd_result, "\n")
Output-
Mean: 30
Median: 30
Standard Deviation: 15.81139
35 | P a g e
Assignment-9
Code-
student_data <- [Link](
Name = c("Samrat", "Srijit", "Rohit", "Rouank", "Suvendu", "Akash"),
Age = c(22, 24, 23, 21, 25, 30),
Score = c(88, 92, 79, 85, 90, 100)
)
boxplot(student_data$Score,
main = "Boxplot of Student Scores",
ylab = "Score",
col = "lightblue",
border = "darkblue")
outliers <- [Link](student_data$Score)$out
print(outliers)
Output-
numeric(0)
36 | P a g e
Assignment-10
[Link] R to generate the frequency distribution of a categorical variable.
Code-
categories <- c("Apple", "Banana", "Apple", "Orange", "Banana", "Apple", "Grapes", "Orange", "Banana", "Grapes")
frequency_distribution <- table(categories)
print(frequency_distribution)
frequency_df <- [Link](frequency_distribution)
colnames(frequency_df) <- c("Category", "Frequency")
print(frequency_df)
barplot(frequency_distribution,
main = "Frequency Distribution of Categories",
xlab = "Categories",
ylab = "Frequency",
col = "lightblue")
Output-
categories
Apple Banana Grapes Orange
3 3 2 2
Category Frequency
1 Apple 3
2 Banana 3
3 Grapes 2
4 Orange 2
37 | P a g e
[Link] a histogram for a numerical column in a [Link] and
interpretthe shape of the histogram(e.g.,skewness,modality).
Code-
[Link](123)
data <- [Link](values = rnorm(1000, mean = 50, sd = 10))
hist(data$values,
main = "Histogram of Values",
xlab = "Values",
ylab = "Frequency",
col = "lightblue",
border = "black",
breaks = 30)
Output-
38 | P a g e
Assignment-11
[Link] a dataset to a CSV file and read it back into R. Display the
contents of the loaded data.
Code-
data <- [Link](
Name = c("Samrat", "Srijit", "Rounak"),
Age = c(25, 30, 35),
City = c("New York", "Los Angeles", "Chicago")
)
print(data)
[Link](data, "C:/Users/Samrat Pal/Downloads/sample_data.csv", [Link] = FALSE)
loaded_data <- [Link]("C:/Users/Samrat Pal/Downloads/sample_data.csv")
print(loaded_data)
Output-
Code-
library(readxl)
39 | P a g e
excel_data <- read_excel("C:/Users/Samrat Pal/Downloads/sample_data.xlsx")
print(excel_data)
Output-
Name Age City
Code-
library(readr)
csv_file_path <- "C:/Users/Samrat Pal/Downloads/sample_data.csv"
data_frame <- read_csv(csv_file_path)
print(data_frame)
Output-
Rows: 3 Columns: 3
── Column specification
Delimiter: ","
chr (2): Name, City
dbl (1): Age
ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Name Age City
1 Samrat 25 New York
2 Srijit 30 Los Angeles
3 Rounak 35 Chicago
40 | P a g e
[Link] a text file containing tab-delimited data into R and convert
it into a data frame.
Code-
file_path <- "C:/Users/Samrat Pal/Downloads/sample_data.csv"
if ([Link](file_path)) {
data <- [Link](file_path, header = TRUE, sep = "\t")
cat("File successfully read!\n")
str(data)
head(data)
} else {
cat("Error: File does not exist at the specified path.\n")
}
Output-
File successfully read!
'[Link]': 3 obs. of 1 variable:
$ [Link]: chr "Samrat,25,New York" "Srijit,30,Los Angeles" "Rounak,35,Chicago"
[Link]
1 Samrat,25,New York
2 Srijit,30,Los Angeles
3 Rounak,35,Chicago
41 | P a g e
5. Save a subset of a data frame to a new CSV file with a different
name.
Code-
data <- mtcars # using the built-in mtcars dataset
subset_data <- data[data$mpg > 20, ]
[Link](subset_data, file = "subset_mtcars.csv", [Link] = FALSE)
Output-
mpg cyl disp hp drat wt qsec vs am gear carb
42 | P a g e
Assignment-12
[Link] the following plots using a dataset in R:
a) Line plot for numerical data.
Code-
data(mtcars)
plot(mtcars$mpg, type = "l",
col = "blue",
lwd = 2,
xlab = "Index",
ylab = "Miles Per Gallon (mpg)",
main = "Line Plot of MPG")
Output-
43 | P a g e
b) Scatter plot between two variables.
Code-
data(mtcars)
plot(mtcars$hp, mtcars$mpg,
col = "red",
pch = 19,
xlab = "Horsepower",
ylab = "Miles Per Gallon (mpg)",
main = "Scatter Plot: MPG vs Horsepower")
Output-
44 | P a g e
c) Bar chart for categorical data.
Code-
data(mtcars)
cyl_factor <- [Link](mtcars$cyl)
barplot(table(cyl_factor),
col = "lightgreen",
xlab = "Number of Cylinders",
ylab = "Count of Cars",
main = "Bar Chart of Cylinders")
Output-
45 | P a g e
d) Histogram for numerical data.
Code-
data(mtcars)
hist(mtcars$mpg,
col = "lightblue",
border = "black",
xlab = "Miles Per Gallon (mpg)",
main = "Histogram of MPG")
Output-
46 | P a g e
2. Customize the visualizations created in question 14 by adding:
a) Titles, axis labels, and legends.
Code-
[Link]( “ggplot2“)
[Link](“reshape2”)
library(ggplot2)
library(reshape2)
data(mtcars)
cor_matrix <- cor(mtcars)
cor_melted <- melt(cor_matrix)
ggplot(data = cor_melted, aes(x = Var1, y = Var2, fill = value)) +
geom_tile(color = "white") +
scale_fill_gradient2(low = "blue", high = "red", mid = "white",
midpoint = 0, limit = c(-1, 1),
name = "Correlation Coefficient") +
theme_minimal() +
theme([Link].x = element_text(angle = 45, hjust = 1, size = 10),
[Link].y = element_text(size = 10),
[Link] = element_text(hjust = 0.5, size = 14, face = "bold"),
[Link] = "right") +
labs(title = "Heatmap of Correlation Matrix for mtcars Dataset",
x = "Variables",
y = "Variables")
47 | P a g e
Output-
Code-
library,(ggplot2)
library(reshape2)
data(mtcars)
cor_matrix <- cor(mtcars)
cor_melted <- melt(cor_matrix)
ggplot(data = cor_melted, aes(x = Var1, y = Var2, fill = value)) +
geom_tile(color = "black", linetype = "dashed") +
48 | P a g e
scale_fill_gradient2(low = "purple", mid = "white", high = "orange",
midpoint = 0, limit = c(-1, 1),
name = "Correlation Coefficient") +
theme_minimal() +
theme([Link].x = element_text(angle = 45, hjust = 1, size = 10),
[Link].y = element_text(size = 10),
[Link] = element_text(hjust = 0.5, size = 14, face = "bold"),
[Link] = "right") +
labs(title = "Heatmap of Correlation Matrix for mtcars Dataset",
x = "Variables",
y = "Variables")
Output-
49 | P a g e
Assignment-13
[Link]("dplyr”)
library(ggplot2)
library(dplyr)
coord_polar("y") +
theme_void() +
print(pie_chart)
[Link](123)
x = rnorm(100),
y = rnorm(100)
print(scatter_plot)
50 | P a g e
Output-
Code-
library(ggplot2)
library(dplyr)
data <- [Link](
category = rep(c("A", "B", "C"), each = 2),
group = rep(c("Group 1", "Group 2"), times = 3),
values = c(10, 15, 20, 25, 30, 35)
)
grouped_bar_chart <- ggplot(data, aes(x = category, y = values, fill = group)) +
geom_bar(stat = "identity", position = "dodge") + # Use position = "dodge" for grouped bars
51 | P a g e
labs(title = "Grouped Bar Chart", x = "Category", y = "Values") +
theme_minimal()
print(grouped_bar_chart)
Output-
52 | P a g e
ggplot(data = melted_cor, aes(x = Var1, y = Var2, fill = value)) +
geom_tile(color = "white") +
scale_fill_gradient2(low = "blue", high = "red", mid = "white",
midpoint = 0, limit = c(-1,1), space = "Lab",
name="Correlation") +
theme_minimal() +
theme([Link].x = element_text(angle = 45, vjust = 1, hjust = 1)) +
coord_fixed() +
geom_text(aes(label = value), color = "black", size = 3)
Output-
53 | P a g e
Assignment-14
[Link] the covariance between multiple pairs of numerical variables in a
dataset.
Code-
df <- [Link](
height = c(150, 160, 170, 180, 190),
weight = c(65, 72, 78, 85, 90),
age = c(25, 30, 35, 40, 45),
gender = c("F", "M", "M", "F", "M")
)
numeric_df <- df[sapply(df, [Link])]
cov_matrix <- cov(numeric_df)
print(cov_matrix)
Output-
height weight age
height 250.0 157.50 125.00
weight 157.5 99.50 78.75
age 125.0 78.75 62.50
Code-
df <- [Link](
height = c(150, 160, 170, 180, 190),
weight = c(65, 72, 78, 85, 90)
)
correlation <- cor(df$height, df$weight)
print(correlation)
Output-
0.9953501
54 | P a g e
Assignment-15
[Link] a correlation matrix for a dataset and visualize it using a heatmap.
Code-
df <- [Link](
height = c(150, 160, 170, 180, 190),
weight = c(65, 72, 78, 85, 90),
age = c(25, 30, 35, 40, 45)
)
numeric_df <- df[sapply(df, [Link])]
cor_matrix <- cor(numeric_df)
corrplot(cor_matrix,
method = "color",
[Link] = "black",
[Link] = "black",
[Link] = 1.2,
[Link] = 1.1,
col = colorRampPalette(c("blue", "white", "red"))(200))
melted_cor <- melt(cor_matrix)
ggplot(data = melted_cor, aes(x = Var1, y = Var2, fill = value)) +
geom_tile(color = "white") +
geom_text(aes(label = round(value, 2)), color = "white", size = 4) +
scale_fill_gradient2(low = "blue", high = "red", mid = "white",
midpoint = 0, limit = c(-1, 1), space = "Lab",
name = "Correlation") +
theme_minimal() +
coord_fixed() +
labs(title = "Correlation Heatmap", x = "", y = "") +
theme([Link].x = element_text(angle = 45, vjust = 1, hjust = 1))
55 | P a g e
Output-
56 | P a g e
[Link] the strength and direction of relationships between variables
based on the correlation values obtained.
Answer-
Sure! Here's a quick guide to interpreting the strength and direction of relationships based on correlation
values:
1. Direction
• Positive correlation (r > 0): As one variable increases, the other also increases.
• Negative correlation (r < 0): As one variable increases, the other decreases.
2. Strength
(These are general rules; exact interpretation can depend on the field you're working in.)
Example interpretations:
57 | P a g e
Assignment-16
[Link] the regression model output and interpret the following:
a) R-squared value.
Answer-
• Definition: R-squared measures how much of the variability in the dependent variable (outcome) is explained by
the independent variable(s) (predictors).
• Interpretation:
o R-squared = 0% → The model explains none of the variability.
o R-squared = 100% → The model explains all the variability.
• Typical Ranges:
o Higher R-squared (e.g., above 70%) often indicates a good model fit, but context matters (in some fields
like social sciences, 30-50% can still be acceptable).
58 | P a g e
c) p-values of the model terms.
• Definition: p-values test the null hypothesis that the corresponding coefficient is zero (no effect).
• Interpretation:
o p-value < 0.05 → statistically significant (the variable meaningfully contributes to the model).
o p-value ≥ 0.05 → not statistically significant (the variable may not have a meaningful effect).
• Important: A statistically significant term implies evidence that the predictor influences the outcome.
In short:
• High R-squared = better model fit.
• Coefficients tell you the direction and strength of influence.
• Low p-values mean the variables are likely important.
59 | P a g e
Assignment-17
[Link] a regression model using a training dataset. Use it to predict
outcomes for a test dataset.
Code-
train_data <- [Link](
x = c(1, 2, 3, 4, 5),
y = c(2, 4, 5, 4, 5)
)
test_data <- [Link](
x = c(6, 7, 8)
)
model <- lm(y ~ x, data = train_data)
summary(model)
predictions <- predict(model, newdata = test_data)
print(predictions)
Output-
Call:
lm(formula = y ~ x, data = train_data)
Residuals:
1 2 3 4 5
-0.8 0.6 1.0 -0.6 -0.2
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.2000 0.9381 2.345 0.101
x 0.6000 0.2828 2.121 0.124
60 | P a g e
Multiple R-squared: 0.6, Adjusted R-squared: 0.4667
F-statistic: 4.5 on 1 and 3 DF, p-value: 0.124
1 2 3
5.8 6.4 7.0
[Link] the prediction accuracy of the model using the following metrics:
a) Mean Absolute Error (MAE).
Code-
actual <- c(3, 5, 2, 7)
predicted <- c(2.5, 5.5, 2.2, 6.8)
mae_manual <- mean(abs(actual - predicted))
cat("MAE (Manual Calculation):", mae_manual, "\n")
MAE <- function(actual, predicted) {
mean(abs(actual - predicted))
}
mae_function <- MAE(actual, predicted)
cat("MAE (Using Custom Function):", mae_function, "\n")
if (!require(Metrics)) {
[Link]("Metrics")
library(Metrics)
} else {
library(Metrics)
}
mae_metrics <- mae(actual, predicted)
cat("MAE (Using Metrics package):", mae_metrics, "\n")
Output-
MAE (Manual Calculation): 0.35
MAE (Using Custom Function): 0.35
MAE (Using Metrics package): 0.35
61 | P a g e
b) Root Mean Squared Error (RMSE).
Code-
actual <- c(3, 5, 2, 7)
predicted <- c(2.5, 5.5, 2.2, 6.8)
rmse_manual <- sqrt(mean((actual - predicted)^2))
cat("RMSE (Manual Calculation):", rmse_manual, "\n")
RMSE <- function(actual, predicted) {
sqrt(mean((actual - predicted)^2))
}
rmse_function <- RMSE(actual, predicted)
cat("RMSE (Using Custom Function):", rmse_function, "\n")
rmse_metrics <- rmse(actual, predicted)
cat("RMSE (Using Metrics package):", rmse_metrics, "\n")
Output-
RMSE (Manual Calculation): 0.4123106
RMSE (Using Custom Function): 0.4123106
RMSE (Using Metrics package): 0.4123106
62 | P a g e
Assignment-18
1. Implement a k-Nearest Neighbors (kNN) classification model on a dataset.
Evaluate the classification performance.
Code-
[Link]("class")
[Link]("caret")
[Link]("e1071")
library(class)
library(caret)
library(e1071)
data(iris)
[Link](123)
iris <- iris[sample(nrow(iris)), ]
normalize <- function(x) {
return((x - min(x)) / (max(x) - min(x)))
}
iris_norm <- [Link](lapply(iris[1:4], normalize))
iris_norm$Species <- iris$Species
[Link](123)
train_index <- sample(1:nrow(iris_norm), 0.7 * nrow(iris_norm))
train_data <- iris_norm[train_index, ]
test_data <- iris_norm[-train_index, ]
train_X <- train_data[, 1:4]
test_X <- test_data[, 1:4]
train_y <- train_data$Species
test_y <- test_data$Species
k <- 3
predictions <- knn(train = train_X, test = test_X, cl = train_y, k = k)
conf_matrix <- confusionMatrix(predictions, test_y)
print(conf_matrix)
63 | P a g e
Output-
Confusion Matrix and Statistics
Reference
Prediction setosa versicolor virginica
setosa 16 0 0
versicolor 0 8 2
virginica 0 1 18
Overall Statistics
Accuracy : 0.9333
95% CI : (0.8173, 0.986)
No Information Rate : 0.4444
P-Value [Acc > NIR] : 4.158e-12
Kappa : 0.8961
Statistics by Class:
64 | P a g e
2. Build a decision tree model using a dataset. Visualize the tree structure.
Code-
[Link]("rattle")
[Link]("rpart")
[Link]("[Link]")
library(rattle)
library(rpart)
library([Link])
data(wine, package = "rattle")
str(wine)
wine$Type <- [Link](wine$Type)
model <- rpart(Type ~ ., data = wine, method = "class")
[Link](model,
type = 2,
extra = 104,
[Link] = TRUE,
main = "Decision Tree for Wine Classification")
Output-
65 | P a g e
3. Evaluate the classification models using the following metrics:
a) Precision.
b) Recall.
c) F1-Score.
Code-
[Link]("caret")
[Link]("e1071")
library(caret)
library(e1071)
[Link](123)
index <- createDataPartition(iris$Species, p = 0.7, list = FALSE)
train_data <- iris[index, ]
test_data <- iris[-index, ]
library(rpart)
model <- rpart(Species ~ ., data = train_data, method = "class")
predictions <- predict(model, newdata = test_data, type = "class")
conf_mat <- confusionMatrix(predictions, test_data$Species)
print(conf_mat)
cm <- table(Predicted = predictions, Actual = test_data$Species)
precision <- diag(cm) / colSums(cm)
recall <- diag(cm) / rowSums(cm)
f1 <- 2 * (precision * recall) / (precision + recall)
metrics <- [Link](Precision = precision,
Recall = recall,
F1_Score = f1)
print(metrics)
Output-
Confusion Matrix and Statistics
Reference
66 | P a g e
Prediction setosa versicolor virginica
setosa 15 0 0
versicolor 0 14 2
virginica 0 1 13
Overall Statistics
Accuracy : 0.9333
95% CI : (0.8173, 0.986)
No Information Rate : 0.3333
P-Value [Acc > NIR] : < 2.2e-16
Kappa : 0.9
Statistics by Class:
67 | P a g e
Assignment-19
[Link] the Boston dataset from the MASS package to predict medv (median home value)
based on lstat (percentage of lower status population). Evaluate the residuals and
R-squared value.
Code-
[Link]("MASS
library(MASS)
data("Boston")
head(Boston)
model <- lm(medv ~ lstat, data = Boston)
summary(model)
r_squared <- summary(model)$[Link]
cat("R-squared:", r_squared, "\n")
plot(Boston$lstat, Boston$medv,
xlab = "LSTAT (% lower status population)",
ylab = "MEDV (Median home value)",
main = "Linear Regression: MEDV ~ LSTAT",
pch = 20, col = "blue")
abline(model, col = "red", lwd = 2)
68 | P a g e
Output-
69 | P a g e
Assignment-20
Fit a polynomial regression model to predict mpg based on wt and visualize
the results with a smooth curve.
Code-
data(mtcars) # Load the mtcars dataset (contains mpg and wt)
model_poly <- lm(mpg ~ poly(wt, 2), data = mtcars)
summary(model_poly)
wt_seq <- seq(min(mtcars$wt), max(mtcars$wt), [Link] = 100)
mpg_pred <- predict(model_poly, newdata = [Link](wt = wt_seq))
plot(mtcars$wt, mtcars$mpg,
xlab = "Weight (wt)",
ylab = "Miles per Gallon (mpg)",
main = "Polynomial Regression: MPG vs Weight",
pch = 16, col = "blue")
lines(wt_seq, mpg_pred, col = "red", lwd = 2)
Output-
70 | P a g e
Assignment-21
[Link] the rpart package to build a decision tree classifier for the iris dataset,
predicting the species of flowers.
Code-
[Link]("rpart")
[Link]("[Link]")
library(rpart)
library([Link])
data(iris)
model <- rpart(Species ~ ., data = iris, method = "class")
summary(model)
[Link](model,
type = 2, # Labels all nodes
extra = 104, # Displays class probabilities and percentages
[Link] = TRUE,
main = "Decision Tree for Iris Species Classification")
Output-
71 | P a g e
Assignment-22
[Link] the class package to build a KNN classifier for the iris dataset.
Experiment with different values of k.
Code-
[Link]("class")
[Link]("caret") # for confusion matrix and performance metrics
library(class)
library(caret)
data(iris)
normalize <- function(x) {
return((x - min(x)) / (max(x) - min(x)))
}
iris_norm <- [Link](lapply(iris[, 1:4], normalize))
iris_norm$Species <- iris$Species # Append target variable back
[Link](123)
train_index <- createDataPartition(iris_norm$Species, p = 0.7, list = FALSE)
train_data <- iris_norm[train_index, ]
test_data <- iris_norm[-train_index, ]
train_x <- train_data[, 1:4]
train_y <- train_data$Species
test_x <- test_data[, 1:4]
test_y <- test_data$Species
for (k in c(1, 3, 5, 7, 9)) {
cat("\nResults for k =", k, "\n")
pred <- knn(train = train_x, test = test_x, cl = train_y, k = k)
cm <- confusionMatrix(pred, test_y)
print(cm$table)
cat("Accuracy:", round(cm$overall['Accuracy'], 4), "\n")
}
72 | P a g e
Output-
Results for k = 1
Reference
Prediction setosa versicolor virginica
setosa 15 0 0
versicolor 0 14 2
virginica 0 1 13
Accuracy: 0.9333
Results for k = 3
Reference
Prediction setosa versicolor virginica
setosa 15 0 0
versicolor 0 14 2
virginica 0 1 13
Accuracy: 0.9333
Results for k = 5
Reference
Prediction setosa versicolor virginica
setosa 15 0 0
versicolor 0 14 2
virginica 0 1 13
Accuracy: 0.9333
Results for k = 7
Reference
Prediction setosa versicolor virginica
setosa 15 0 0
versicolor 0 15 2
virginica 0 0 13
Accuracy: 0.9556
73 | P a g e
Results for k = 9
Reference
Prediction setosa versicolor virginica
setosa 15 0 0
versicolor 0 15 1
virginica 0 0 14
Accuracy: 0.9778
74 | P a g e
Assignment-23
Compare classification models (e.g., logistic regression, decision tree,
SVM) on the iris dataset using metrics such as accuracy, precision, recall,
and F1 score.
Code-
[Link]("nnet")
[Link]("rpart")
[Link]("e1071")
[Link]("caret")
library(nnet)
library(rpart)
library(e1071)
library(caret)
data(iris)
[Link](123)
train_index <- createDataPartition(iris$Species, p = 0.7, list = FALSE)
train_data <- iris[train_index, ]
test_data <- iris[-train_index, ]
log_model <- multinom(Species ~ ., data = train_data)
tree_model <- rpart(Species ~ ., data = train_data, method = "class")
svm_model <- svm(Species ~ ., data = train_data)
log_pred <- predict(log_model, test_data)
tree_pred <- predict(tree_model, test_data, type = "class")
svm_pred <- predict(svm_model, test_data)
evaluate_model <- function(pred, actual) {
cm <- confusionMatrix(pred, actual)
list(
Accuracy = cm$overall['Accuracy'],
Precision = cm$byClass[, 'Precision'],
Recall = cm$byClass[, 'Recall'],
75 | P a g e
F1 = cm$byClass[, 'F1']
)
}
log_metrics <- evaluate_model(log_pred, test_data$Species)
tree_metrics <- evaluate_model(tree_pred, test_data$Species)
svm_metrics <- evaluate_model(svm_pred, test_data$Species)
print(log_metrics)
print(tree_metrics)
print(svm_metrics)
Output-
# weights: 18 (10 variable)
initial value 115.354290
iter 10 value 11.160147
iter 20 value 3.325479
iter 30 value 2.713763
iter 40 value 2.623668
iter 50 value 2.409177
iter 60 value 2.346975
iter 70 value 2.246318
iter 80 value 2.223840
iter 90 value 1.930046
iter 100 value 1.883252
final value 1.883252
stopped after 100 iterations
$Accuracy
Accuracy
76 | P a g e
0.9555556
$Precision
Class: setosa Class: versicolor Class: virginica
1.0000000 0.8823529 1.0000000
$Recall
Class: setosa Class: versicolor Class: virginica
1.0000000 1.0000000 0.8666667
$F1
Class: setosa Class: versicolor Class: virginica
1.0000000 0.9375000 0.9285714
$Accuracy
Accuracy
0.9333333
$Precision
Class: setosa Class: versicolor Class: virginica
1.0000000 0.8750000 0.9285714
$Recall
Class: setosa Class: versicolor Class: virginica
1.0000000 0.9333333 0.8666667
$F1
Class: setosa Class: versicolor Class: virginica
1.0000000 0.9032258 0.8965517
🔹 SVM Metrics:
77 | P a g e
$Accuracy
Accuracy
0.9333333
$Precision
Class: setosa Class: versicolor Class: virginica
1.0000000 0.8750000 0.9285714
$Recall
Class: setosa Class: versicolor Class: virginica
1.0000000 0.9333333 0.8666667
$F1
Class: setosa Class: versicolor Class: virginica
1.0000000 0.9032258 0.8965517
78 | P a g e