0% found this document useful (0 votes)
2 views26 pages

Part A & B R Lab Programs

The document outlines various R programming exercises, including matrix operations, finding roots of quadratic equations, generating prime numbers, and statistical analyses. Each exercise provides a description, purpose, and sample code for implementation. The exercises cover a range of topics such as data manipulation, statistical distributions, and graphical representations.

Uploaded by

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

Part A & B R Lab Programs

The document outlines various R programming exercises, including matrix operations, finding roots of quadratic equations, generating prime numbers, and statistical analyses. Each exercise provides a description, purpose, and sample code for implementation. The exercises cover a range of topics such as data manipulation, statistical distributions, and graphical representations.

Uploaded by

Deeksha chethan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SL.

DESCRIPTION PAGE
NO No
PART A - R PROGRAMMING

1 Program to create a 3 X 3 matrices A and B and perform the


following operations
a. AT .B
b. B T .([Link] )
c. ([Link] ).BT
d. [([Link] )+([Link] )-100I3] -1
2 R program to find roots of quadratic equation using user
defined function. Test the program user supplied values
for all possible cases.
3 Program to generate prime numbers between two given
numbers
4 R program to create a list containing strings, numbers,
vectors and logical values and do the following
manipulations over the list
a. Access the first element in the list
b. Give the names to the elements in the list
c. Add element at some positions in the list
d. Remove the element
e. print the first and third element
f. Update the third element
5 Purpose: The following table shows the time taken (in
minutes) by 100 students to travel to school on a
particular day.

a. Draw the histogram


b. Draw frequency polygon
6 R program to create a Data Frame with following details
and do the following operations.
itemCode itemCategory ItemPrice
1001 Electronics 700
1002 Desktop 300
Supplies
1003 Office Supplies 350
1004 USB 400
1005 CD Drive 800
a. Subset the Data frame and display the details of only
those items whose price is greater than or equal to 350.
b. Subset the Data frame and display only the items where
the category is either “Office Supplies” or “Desktop
Supplies”
c. Subset the Data frame and display the items where the
Itemprice between 300 and 700
d. Compute the sum of all ItemPrice
e. Create another Data Frame called “item-details” with
three different fields itemCode, ItemQtyonHand and
ItemReorderLvl and merge the two frames.
7 Create a factor marital_status with levels Married,
single, divorced. Perform the following operations on this
factor
a. Check the variable is a factor
b. Access the 2nd and 4th element in the factor
c. Remove third element from the factor
d. Add new level widowed to the factor and add the same
level to the factor marital_status
e. Modify the second element of the factor
8 R language Script for following operation on Iris Data Set
1. Load the Iris Dataset
2. View first six rows of iris dataset
3. Summarize iris dataset
4. Display number of rows and columns
5. Display column names of dataset.
6. Create histogram of values for sepal length
7. Create scatterplot of sepal width vs. sepal length
8. Create boxplot of sepal width vs. sepal length
9. Find Pearson correlation between [Link] and
[Link]
10. Create correlation matrix for dataset
PART B

1 R program to create a Vector containing following 8 values


and perform the following operations. 4 3 0 5 2 9 4 5
a. Find mean, median, mode.
b. Find the range.
c. Find the 35th and 78th percentile.
d. Find the sample variance and sample standard deviation
e. Find the interquartile range.
f. Find the z-score for each value.
2 R script to find the correlation coefficient and type of
correlation between advertisement expenses and sales
volume using Karl Pearson’s coefficient of correlation
method (Direct Method).

Firm 1 2 3 4 5 6 7 8 9 10
Advertise 11 13 14 16 16 15 15 14 13 13
ment
Expenses
([Link]
Lakhs)
Sales 50 50 55 60 65 65 65 60 60 50
Volume
([Link]
Lakhs)
3 R script to compute the regression equation of y on x and
x on y from the following data. Predict the value of y
when x=7
X 2 4 5 6 8 11
Y 18 12 10 8 7 5

4 The times taken by a large group of students to complete a


piece of homework, T minutes, are Normally distributed
with a mean of 57 minutes and standard deviation of 6.5.
Find the probability that the time taken by a random
student from the group to complete this homework will be
less than 60 minutes.
Write R script to Find the probability that the time taken
by a random student from the group to complete this
homework
a) Will be less than 60 minutes
b) Between 50 and 80 minutes
5 R script to perform the following using binomial
distribution
i. If n=4 and p=0.10 , find P(x=3)
ii. If n=12 and p=0.45, find P(5<=x<=7)
6 Perform the following using uniform distribution between
200 and 240 i. P(x>230) ii. P(205≤x≤220)
7 For the given scores of max vertical jumps before and
after the training program. Test whether the training
program is helpful to the students (Use Paired t-test).Use
α=0.01

8 A company has three manufacturing plants, and company officials want to


determine whether there is difference in the average age of workers at the three
locations. The following data are the ages of five randomly selected workers at
each plant. Perform a one-way ANOVA to determine whether there is a significant
difference in the mean ages of the workers at three plants. Use α=0.01. Write R
script for the above problem.
Plant(Employee Ages)
1 2 3
29 32 25
27 33 24
30 31 24
27 34 25
28 30 25
Exercise No. 1
Purpose:

#Write a program to create a 3 X 3 matrices A and B and perform the


following operations
#a. AT .B
#b. B T .([Link] )
#c. ([Link] ).BT
#d. [([Link] )+([Link] )-100I3] -1

[Link]<-function(){
order=[Link](readline("Enter the matrix order"))
# To read matrix A elements & store it in a vector
myvector=scan(n=order*order)
# Create matricx A
A=matrix(myvector, nrow=order)
# To read matrix B elements & store it in a vector
myvector=scan(n=order*order)
B=matrix(myvector, nrow=order)
# Print matrices A and B
print("Matrix A:")
print(A)
print("Matrix B:")
print(B)
# Calculate the transpose of the matrix A
A_transpose <- t(A)

# Calculate the transpose of the matrix B


B_transpose <- t(B)
# a. AT .B
# Print Transpose of matrix A and Transpose of matrix B
print("Transpose of Matrix A:")
print(A_transpose)
print("Transpose of Matrix B:")
print(B_transpose)

# Calculate the product of Transpose of A and B


tAB <- A_transpose %*% B

# Print the product matrix


print("Transpose of Matrix AxB:")
print(tAB)

# b. B T .([Link] )
# Calculate the product of transpose of B and [Link] of A
tBtAA <- B_transpose %*% (A_transpose%*%A)

# Print the product matrix


print("Transpose of Matrix B T .([Link] ):")
print(tBtAA)

# c. ([Link] ).BT
tAAtB <- (A_transpose%*%A) %*% B_transpose
# Print the product matrix
print("([Link] ).BT :")
print(tAAtB)

# d. [([Link] )+([Link] )-100I3] -1

invers <-solve(((B%*%B_transpose)+(A%*%A_transpose))-
(100*(matrix(c(1,0,0,0,1,0,0,0,1),nrow=3))))
print(invers)
}
[Link]()
Output:

> source("G:\\R\\palab1.R")
Enter the matrix order3
1: 3
2: 1
3: 2
4: 3
5: 4
6: 5
7: 2
8: 3
9: 2
Read 9 items
1: 6
2: 4
3: 2
4: 1
5: 4
6: 5
7: 1
8: 3
9: 6
Read 9 items
[1] "Matrix A:"
[,1] [,2] [,3]
[1,] 3 3 2
[2,] 1 4 3
[3,] 2 5 2
[1] "Matrix B:"
[,1] [,2] [,3]
[1,] 6 1 1
[2,] 4 4 3
[3,] 2 5 6
[1] "Transpose of Matrix A:"
[,1] [,2] [,3]
[1,] 3 1 2
[2,] 3 4 5
[3,] 2 3 2
[1] "Transpose of Matrix B:"
[,1] [,2] [,3]
[1,] 6 4 2
[2,] 1 4 5
[3,] 1 3 6
[1] "Transpose of Matrix AxB:"
[,1] [,2] [,3]
[1,] 26 17 18
[2,] 44 44 45
[3,] 28 24 23
[1] "Transpose of Matrix B T .([Link] ):"
[,1] [,2] [,3]
[1,] 202 394 224
[2,] 171 363 210
[3,] 161 341 199
[1] "([Link] ).BT :"
[,1] [,2] [,3]
[1,] 120 187 221
[2,] 216 376 464
[3,] 123 215 268
[,1] [,2] [,3]
[1,] -0.008107930 0.005479222 0.008140901
[2,] 0.005479222 -0.003333094 0.008176870
[3,] 0.008140901 0.008176870 -0.002074191
>

Exercise No. 2:
Purpose: R program to find roots of quadratic equation using user
defined function. Test the program user supplied values for all
possible cases.

# Function to calculate the roots of a quadratic equation


quadratic_roots <- function(a, b, c) {
# Calculate the discriminant
discriminant <- b^2 - 4 * a * c

# Check the nature of roots


if (discriminant > 0) {
# Two distinct real roots
root1 <- (-b + sqrt(discriminant)) / (2 * a)
root2 <- (-b - sqrt(discriminant)) / (2 * a)
cat("Roots are real and distinct:\n")
cat("Root 1 =", root1, "\n")
cat("Root 2 =", root2, "\n")
} else if (discriminant == 0) {
# Two equal real roots
root <- -b / (2 * a)
cat("Roots are real and equal:\n")
cat("Root =", root, "\n")
} else {
# Complex roots
real_part <- -b / (2 * a)
imaginary_part <- sqrt(abs(discriminant)) / (2 * a)
cat("Roots are complex:\n")
cat("Root 1 =", real_part, "+", imaginary_part, "i\n")
cat("Root 2 =", real_part, "-", imaginary_part, "i\n")
}
}

# Function to test the quadratic_roots function with user-supplied


values
test_quadratic_roots <- function() {
# Test cases with user-supplied values
test_cases <- list(
list(a = 1, b = 5, c = 6), # Two distinct real roots
list(a = 1, b = -6, c = 9), # Two equal real roots
list(a = 2, b = 3, c = 10) # Complex roots
)

cat("Testing quadratic_roots function with user-supplied values:\n")

for (i in 1:length(test_cases)) {
cat("\nTest Case", i, ":\n")
quadratic_roots(test_cases[[i]]$a, test_cases[[i]]$b,
test_cases[[i]]$c)
}
}

# Test the program


test_quadratic_roots()

# Input coefficients from the user


a <- [Link](readline("Enter coefficient a: "))
b <- [Link](readline("Enter coefficient b: "))
c <- [Link](readline("Enter coefficient c: "))
# Calculate and display the roots
quadratic_roots(a, b, c)

Output:

Test Case 1 :
Discriminant: 1
Roots are real and distinct:
Root 1 = -2
Root 2 = -3

Test Case 2 :
Discriminant: 0
Roots are real and equal:
Root = 3

Test Case 3 :
Discriminant: -71
Roots are complex:
Root 1 = -0.75 + 2.106537 i
Root 2 = -0.75 - 2.106537 i

Enter coefficient a: 2
Enter coefficient b: -1
Enter coefficient c: 2
Discriminant: -15
Roots are complex:
Root 1 = 0.25 + 0.9682458 i
Root 2 = 0.25 - 0.9682458 i
Exercise No. 3
Purpose: Program to generate prime numbers between two given numbers

# Function to check if a number is prime


is_prime <- function(n) {
if (n <= 1) {
return(FALSE)
}
if (n == 2) {
return(TRUE)
}
if (n %% 2 == 0) {
return(FALSE)
}
max_divisor <- floor(sqrt(n))
for (i in 3:max_divisor) {
if (n %% i == 0) {
return(FALSE)
}
}
return(TRUE)
}
# Function to generate prime numbers between two given numbers
generate_primes <- function(start, end) {
primes <- c()
for (num in start:end) {
if (is_prime(num)) {
primes <- c(primes, num)
}
}
return(primes)
}
# Example usage:
start <- 10
end <- 50
prime_numbers <- generate_primes(start, end)
print(prime_numbers)
# Input the range from the user
start<-[Link](readline("Enter the starting number: "))
end<-[Link](readline("Enter the ending number: "))
cat("Prime numbers between", start, "and", end, "are:\n")
for (num in start:end)
{
if (is_prime(num))
print(num)
}

Output:

> source("G:\\R\\prlab3.R") Enter the starting number: 2


[1] 11 13 17 19 23 29 31 37 41 Enter the ending number: 31
43 47
Prime numbers between 2 and 31 [1] 13
are: [1] 17
[1] 2 [1] 19
[1] 5 [1] 23
[1] 7 [1] 29
[1] 11 [1] 31
Exercise No. 4
Purpose: R program to create a list containing strings, numbers,
vectors and logical values and do the following manipulations over the
list
a. Access the first element in the list
b. Give the names to the elements in the list
c. Add element at some positions in the list
d. Remove the element
e. print the first and third element
f. Update the third element

# Create a list
my_list <- list(
strings = “hello”,
numbers = 123,
vectors = c(1, 2, 3),
logical_values = TRUE
)
# print given list
cat(“Given List is: \n”)
print(my_list)

# a. Access the first element in the list


first_element <- my_list[[1]]
cat(“First element:”, first_element, “\n”)

# b. Give names to the elements in the list


names(my_list) <- c(“str”, “num”, “vec”, “logical”)

# c. Add an element at some positions in the list


my_list[[“new_element”]] <- “new”
cat(“List after adding new element:\n”)
print(my_list)

# d. Remove the element


my_list[[“new_element”]] <- NULL
cat(“List after removing new element:\n”)
print(my_list)

# e. Print the first and third element


first <- my_list[[1]]
third <- my_list[[3]]
cat(“First element:”, first, “\n”)
cat(“Third element:”, third, “\n”)

# f. Update the third element


my_list[[“vec”]] <- c(4, 5, 6)
cat(“List after updating third element:\n”)
print(my_list)
Output:
> source(“G:\\R\\prlab4.R”)
Given List is:
$strings
[1] “hello”

$numbers
[1] 123

$vectors
[1] 1 2 3

$logical_values
[1] TRUE

First element: hello


List after adding new element:
$str
[1] “hello”

$num
[1] 123

$vec
[1] 1 2 3

$logical
[1] TRUE

$new_element
[1] “new”

List after removing new element:


$str
[1] “hello”

$num
[1] 123

$vec
[1] 1 2 3

$logical
[1] TRUE

First element: hello


Third element: 1 2 3
List after updating third element:
$str
[1] “hello”

$num
[1] 123

$vec
[1] 4 5 6

$logical
[1] TRUE

Exercise No. 5
Purpose: The following table shows the time taken (in minutes) by 100
students to travel to school on a particular day.

a. Draw the histogram


b. Draw frequency polygon

#histogram
# Define the breaks of the bins based on your intervals
# The breaks are the minimum and maximum of each interval
breaks <- c(0, 5, 10, 15, 20, 25)
# Number of students in each interval
students <- c(5, 25, 40, 17, 13)
# Create the histogram
hist(rep(breaks[-length(breaks)], times=students), breaks=breaks,
freq=TRUE,
main="Histogram of Student Travel Times", xlab="Travel Time
(minutes)",
ylab="Number of Students", col="blue", border="black", right=FALSE)
#Frequency polygon
# Time intervals (midpoints of each bin)
time_midpoints <- c(2.5, 7.5, 12.5, 17.5, 22.5)
# Number of students in each interval
no_of_students <- c(5, 25, 40, 17, 13)
# Plot the frequency polygon
plot(time_midpoints, no_of_students, type="b", [Link]=FALSE,
xlab="Travel Time (minutes)", ylab="Number of Students",
main="Frequency Polygon of Student Travel Times",
pch=19, col="blue")

Output:
Exercise No. 6
Purpose: R program to create a Data Frame with following details and do
the following operations.
itemCode itemCategory ItemPrice
1001 Electronics 700
1002 Desktop 300
Supplies
1003 Office Supplies 350
1004 USB 400
1005 CD Drive 800

a. Subset the Data frame and display the details of only those items
whose price is greater than or equal to 350.
b. Subset the Data frame and display only the items where the category
is either “Office Supplies” or “Desktop Supplies”
c. Subset the Data frame and display the items where the Itemprice
between 300 and 700
d. Compute the sum of all ItemPrice
e. Create another Data Frame called “item-details” with three different
fields itemCode, ItemQtyonHand and ItemReorderLvl and merge the two
frames.

# Creating the initial Data Frame


item_data <- [Link](
itemCode = c(1001, 1002, 1003, 1004, 1005),
itemCategory = c("Electronics", "Desktop Supplies", "Office
Supplies", "USB", "CD Drive"),
ItemPrice = c(700, 300, 350, 400, 800)
)

# Displaying the initial Data Frame


print("Initial Data Frame:")
print(item_data)

# a. Subset the Data frame and display the details of only those
items whose price is greater than or equal to 350
subset_a <- subset(item_data, ItemPrice >= 350)
print("Subset of items with price greater than or equal to 350:")
print(subset_a)

# b. Subset the Data frame and display only the items where the
category is either “Office Supplies” or “Desktop Supplies”
subset_b <- subset(item_data, itemCategory %in% c("Office Supplies",
"Desktop Supplies"))
print("Subset of items with category 'Office Supplies' or 'Desktop
Supplies':")
print(subset_b)

# c. Subset the Data frame and display the items where the Itemprice
between 300 and 700
subset_c <- subset(item_data, ItemPrice >= 300 & ItemPrice <= 700)
print("Subset of items with price between 300 and 700:")
print(subset_c)

# d. Compute the sum of all ItemPrice


total_price <- sum(item_data$ItemPrice)
print("Total sum of ItemPrice:")
print(total_price)

# e. Create another Data Frame called item-details with three


different fields itemCode, ItemQtyonHand and ItemReorderLvl and
merge the two frames.
# Assuming item details are not provided in this script, let's
create a sample item-details data frame with random values
item_details <- [Link](
itemCode = c(1001, 1002, 1003, 1004, 1005),
ItemQtyonHand = c(10, 20, 15, 5, 25),
ItemReorderLvl = c(5, 10, 8, 3, 15)
)

# Merging the two data frames based on itemCode


merged_data <- merge(item_data, item_details, by = "itemCode")
print("Merged Data Frame:")
print(merged_data)

Output:

> source("G:\\R\\prlab6.R")
[1] "Initial Data Frame:"
itemCode itemCategory ItemPrice
1 1001 Electronics 700
2 1002 Desktop Supplies 300
3 1003 Office Supplies 350
4 1004 USB 400
5 1005 CD Drive 800
[1] "Subset of items with price greater than or equal to 350:"
itemCode itemCategory ItemPrice
1 1001 Electronics 700
3 1003 Office Supplies 350
4 1004 USB 400
5 1005 CD Drive 800
[1] "Subset of items with category 'Office Supplies' or 'Desktop
Supplies':"
itemCode itemCategory ItemPrice
2 1002 Desktop Supplies 300
3 1003 Office Supplies 350
[1] "Subset of items with price between 300 and 700:"
itemCode itemCategory ItemPrice
1 1001 Electronics 700
2 1002 Desktop Supplies 300
3 1003 Office Supplies 350
4 1004 USB 400
[1] "Total sum of ItemPrice:"
[1] 2550
[1] "Merged Data Frame:"
itemCode itemCategory ItemPrice ItemQtyonHand ItemReorderLvl
1 1001 Electronics 700 10 5
2 1002 Desktop Supplies 300 20 10
3 1003 Office Supplies 350 15 8
4 1004 USB 400 5 3
5 1005 CD Drive 800 25 15
>

Exercise No. 7
Purpose: Create a factor marital_status with levels Married, single,
divorced. Perform the following operations on this factor
a. Check the variable is a factor
b. Access the 2nd and 4th element in the factor
c. Remove third element from the factor
d. Add new level widowed to the factor and add the same level to the
factor marital_status
e. Modify the second element of the factor

# Create the factor variable


marital_status <- factor(c("Married", "Single", "Divorced"))
print("Original List")
print(marital_status)

# a. Check if the variable is a factor


print("Is 'marital_status' a factor?")
print([Link](marital_status))
# b. Access the 2nd and 4th element in the factor
print("2nd and 4th elements in 'marital_status':")
print(marital_status[c(2, 4)])
# c. Remove the third element from the factor
marital_status <- marital_status[-3]
print("After removing the third element:")
print(marital_status)
# d. Add new level 'Widowed' to the factor and add the same level to
the factor 'marital_status'
marital_status <- factor(marital_status, levels
=c(levels(marital_status), "Widowed"))
print("After adding 'Widowed' level:")
print(marital_status)
# e. Modify the second element of the factor
marital_status[2] <- "Widowed"
print("After modifying the second element:")
print(marital_status)
Output:
> source("G:\\R\\prlab7.R")
[1] "Original List"
[1] Married Single Divorced
Levels: Divorced Married Single
[1] "Is 'marital_status' a factor?"
[1] TRUE
[1] "2nd and 4th elements in 'marital_status':"
[1] Single <NA>
Levels: Divorced Married Single
[1] "After removing the third element:"
[1] Married Single
Levels: Divorced Married Single
[1] "After adding 'Widowed' level:"
[1] Married Single
Levels: Divorced Married Single Widowed
[1] "After modifying the second element:"
[1] Married Widowed
Levels: Divorced Married Single Widowed
>

Exercise No. 8
Purpose: R language Script for following operation on Iris Data Set
1. Load the Iris Dataset
2. View first six rows of iris dataset
3. Summarize iris dataset
4. Display number of rows and columns
5. Display column names of dataset.
6. Create histogram of values for sepal length
7. Create scatterplot of sepal width vs. sepal length
8. Create boxplot of sepal width vs. sepal length
9. Find Pearson correlation between [Link] and [Link]
10. Create correlation matrix for dataset

# Load the Iris dataset


data(iris)

# View first six rows of the Iris dataset


print("First six rows of Iris dataset:")
print(head(iris))

# Summarize Iris dataset


print("Summary of Iris dataset:")
print(summary(iris))

# Display number of rows and columns


print("Number of rows and columns in Iris dataset:")
print(dim(iris))

# Display column names of the dataset


print("Column names of the dataset:")
print(colnames(iris))

# Create histogram of values for sepal length


hist(iris$[Link], main="Histogram of Sepal Length", xlab="Sepal
Length", ylab="Frequency")
# Create scatterplot of sepal width vs. sepal length
plot(iris$[Link], iris$[Link], main="Scatterplot of Sepal
Width vs. Sepal Length", xlab="Sepal Length", ylab="Sepal Width")

# Create boxplot of sepal width vs. sepal length


boxplot(iris$[Link] ~ iris$[Link], main="Boxplot of Sepal
Width vs. Sepal Length", xlab="Sepal Length", ylab="Sepal Width")

# Find Pearson correlation between [Link] and [Link]


correlation <- cor(iris$[Link], iris$[Link])
print("Pearson correlation between [Link] and [Link]:")
print(correlation)

# Create correlation matrix for the dataset


correlation_matrix <- cor(iris[,1:4])
print("Correlation matrix for the Iris dataset:")
print(correlation_matrix)

Output:
> source("G:\\R\\prlab8.R")
[1] "First six rows of Iris dataset:"
[Link] [Link] [Link] [Link] Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
[1] "Summary of Iris dataset:"
[Link] [Link] [Link] [Link]
Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100
1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300
Median :5.800 Median :3.000 Median :4.350 Median :1.300
Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199
3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800
Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500
Species
setosa :50
versicolor:50
virginica :50

[1] "Number of rows and columns in Iris dataset:"


[1] 150 5
[1] "Column names of the dataset:"
[1] "[Link]" "[Link]" "[Link]" "[Link]"
"Species"
[1] "Pearson correlation between [Link] and [Link]:"
[1] 0.8717538
[1] "Correlation matrix for the Iris dataset:"
[Link] [Link] [Link] [Link]
[Link] 1.0000000 -0.1175698 0.8717538 0.8179411
[Link] -0.1175698 1.0000000 -0.4284401 -0.3661259
[Link] 0.8717538 -0.4284401 1.0000000 0.9628654
[Link] 0.8179411 -0.3661259 0.9628654 1.0000000
>
Exercise No.1(Part B)
Purpose: R program to create a Vector containing following 8 values and
perform the following operations. 4 3 0 5 2 9 4 5
a. Find mean, median, mode.
b. Find the range.
c. Find the 35th and 78th percentile.
d. Find the sample variance and sample standard deviation
e. Find the interquartile range.
f. Find the z-score for each value.

# Create the vector


values <- c(4, 3, 0, 5, 2, 9, 4, 5)

# a. Find mean, median, mode


mean_value <- mean(values)
median_value <- median(values)
mode_value <- [Link](names(sort(table(values), decreasing = TRUE)
[1]))

print("Mean, Median, and Mode:")


print(mean_value)
print(median_value)
print(mode_value)

# b. Find the range


range_value <- max(values) - min(values)
print("Range:")
print(range_value)

# c. Find the 35th and 78th percentile


percentile_35 <- quantile(values, 0.35)
percentile_78 <- quantile(values, 0.78)

print("35th and 78th Percentile:")


print(percentile_35)
print(percentile_78)
# d. Find the sample variance and sample standard deviation
sample_variance <- var(values)
sample_std_deviation <- sd(values)

print("Sample Variance and Sample Standard Deviation:")


print(sample_variance)
print(sample_std_deviation)

# e. Find the interquartile range


interquartile_range <- IQR(values)
print("Interquartile Range:")
print(interquartile_range)

# f. Find the z-score for each value


z_scores <- scale(values)
print("Z-Scores for each value:")
print(z_scores)

Output:
> source("G:\\R\\prlab9.R")
[1] "Mean, Median, and Mode:"
[1] 4
[1] 4
[1] 4
[1] "Range:"
[1] 9
[1] "35th and 78th Percentile:"
35%
3.45
78%
5
[1] "Sample Variance and Sample Standard Deviation:"
[1] 6.857143
[1] 2.618615
[1] "Interquartile Range:"
[1] 2.25
[1] "Z-Scores for each value:"
[,1]
[1,] 0.0000000
[2,] -0.3818813
[3,] -1.5275252
[4,] 0.3818813
[5,] -0.7637626
[6,] 1.9094065
[7,] 0.0000000
[8,] 0.3818813
attr(,"scaled:center")
[1] 4
attr(,"scaled:scale")
[1] 2.618615
>
Exercise No.2(Part B)
Purpose:R script to find the correlation coefficient and type of
correlation between advertisement expenses and sales volume using Karl
Pearson’s coefficient of correlation method (Direct Method).

Firm 1 2 3 4 5 6 7 8 9 10

Advertisement 11 13 14 16 16 15 15 14 13 13
Expenses
([Link] Lakhs)
Sales Volume 50 50 55 60 65 65 65 60 60 50
([Link] Lakhs)

# Given data (advertisement expenses and sales volume)


advertisement <- c(11,13,14,16,16,15,15,14,13,13)
sales_volume <- c(50,50,55,60,65,65,65,60,60,50)

# Calculate the mean of advertisement expenses and sales volume


mean_advertisement <- mean(advertisement)
mean_sales_volume <- mean(sales_volume)

# Calculate the deviation from mean for both variables


deviation_advertisement <- advertisement - mean_advertisement
deviation_sales_volume <- sales_volume - mean_sales_volume

# Calculate the sum of products of deviations


sum_of_products <- sum(deviation_advertisement *
deviation_sales_volume)

# Calculate the sum of squares of deviations


sum_of_squares_advertisement <- sum(deviation_advertisement^2)
sum_of_squares_sales_volume <- sum(deviation_sales_volume^2)

# Calculate Karl Pearson's correlation coefficient


correlation_coefficient<-sum_of_products/
sqrt(sum_of_squares_advertisement*sum_of_squares_sales_volume)

# Determine the type of correlation


if (correlation_coefficient > 0) {
correlation_type <- "Positive correlation"
} else if (correlation_coefficient < 0) {
correlation_type <- "Negative correlation"
} else {
correlation_type <- "No correlation"
}

# Print the correlation coefficient and type of correlation


print("Correlation coefficient:")
print(correlation_coefficient)
print("Type of correlation:")
print(correlation_type)

Output:
> source("G:\\R\\prlab10.R")
[1] "Correlation coefficient:"
[1] 0.7865665
[1] "Type of correlation:"
[1] "Positive correlation"
>

Exercise No.3(Part B)
Purpose: R script to compute the regression equation of y on x and x on
y from the following data. Predict the value of y when x=7

X 2 4 5 6 8 11

Y 18 12 10 8 7 5

# Given data
x <- c(2,4,5,6,8,11)
y <- c(18,12,10,8,7,5)

# Compute regression equation of y on x


lm_y_on_x <- lm(y ~ x)
summary(lm_y_on_x)

# Extract coefficients
a <- coef(lm_y_on_x)[1] # Intercept
b <- coef(lm_y_on_x)[2] # Slope

# Predict value of y when x = 7


x_new <- 7
y_predicted <- a + b * x_new
print(paste("Predicted value of y when x =", x_new, "is", y_predicted))

# Compute regression equation of x on y


lm_x_on_y <- lm(x ~ y)
summary(lm_x_on_y)
# Extract coefficients
a <- coef(lm_x_on_y)[1] # Intercept
b <- coef(lm_x_on_y)[2] # Slope

# Predict value of x when y = 7


y_new <- 7
x_predicted <- a + b * y_new
print(paste("Predicted value of x when y =", y_new, "is", x_predicted))

Output:
> source("G:\\R\\prlab11.R")
[1] "Predicted value of y when x = 7 is 8.66"
[1] "Predicted value of x when y = 7 is 7.89622641509434"
>

Exercise No.4(Part B)
Purpose: The times taken by a large group of students to complete a
piece of homework, T minutes, are Normally distributed with a mean of
57 minutes and standard deviation of 6.5. Find the probability that the
time taken by a random student from the group to complete this homework
will be less than 60 minutes.
Write R script to Find the probability that the time taken by a random
student from the group to complete this homework
a) Will be less than 60 minutes
b) Between 50 and 80 minutes

# Given parameters
mean <- 57
std_dev <- 6.5

# a) Probability that time taken is less than 60 minutes


prob_less_than_60 <- pnorm(60, mean, std_dev)
print("Probability that time taken is less than 60 minutes:")
print(prob_less_than_60)

# b) Probability that time taken is between 50 and 80 minutes


prob_between_50_80 <- pnorm(80, mean, std_dev) - pnorm(50, mean,
std_dev)
print("Probability that time taken is between 50 and 80 minutes:")
print(prob_between_50_80)

Output:
> source("G:\\R\\prlab12.R")
[1] "Probability that time taken is less than 60 minutes:"
[1] 0.6777938
[1] "Probability that time taken is between 50 and 80 minutes:"
[1] 0.8590415
>

Exercise No.5(Part B)
Purpose: R script to perform the following using binomial distribution
iii. If n=4 and p=0.10 , find P(x=3)
iv. If n=12 and p=0.45, find P(5<=x<=7)

# i. If n=4 and p=0.10 , find P(x=3)


n1 <- 4
p1 <- 0.10
x1 <- 3

prob_x3 <- dbinom(x1, n1, p1)


print("Probability of x=3 when n=4 and p=0.10:")
print(prob_x3)

# ii. If n=12 and p=0.45, find P(5<=x<=7)


n2 <- 12
p2 <- 0.45
x_lower <- 5
x_upper <- 7

prob_5_to_7 <- sum(dbinom(x_lower:x_upper, n2, p2))


print("Probability of 5<=x<=7 when n=12 and p=0.45:")
print(prob_5_to_7)

Output:
> source("G:\\R\\prlab13.R")
[1] "Probability of x=3 when n=4 and p=0.10:"
[1] 0.0036
[1] "Probability of 5<=x<=7 when n=12 and p=0.45:"
[1] 0.583828
>

Exercise No.6(Part B)
Purpose: Perform the following using uniform distribution between 200
and 240 i. P(x>230) ii. P(205≤x≤220)

# Given parameters
a <- 200
b <- 240

# i. P(x>230)
prob_gt_230 <- 1 - punif(230, a, b)
print("Probability of x > 230:")
print(prob_gt_230)

# ii. P(205≤x≤220)
prob_205_to_220 <- punif(220, a, b) - punif(205, a, b)
print("Probability of 205≤x≤220:")
print(prob_205_to_220)

Output:

> source("G:\\R\\prlab14.R")
[1] "Probability of x > 230:"
[1] 0.25
[1] "Probability of 205≤x≤220:"
[1] 0.375
>

Exercise No.7(Part B)
Purpose: Following are the scores of max vertical jumps before and
after the training program. Test whether the training program is
helpful to the students (Use Paired t-test).Use α=0.01

# Given scores of max vertical jumps before and after training program
before <-
c(22,20,19,24,25,25,28,22,30,27,24,18,16,19,19,28,24,25,25,23)
after <- c(24,22,19,22,28,26,28,24,30,29,25,20,17,18,18,28,26,27,27,24)

# Perform paired t-test


result <- [Link](before, after, paired=TRUE, alternative="less",
[Link]=0.99)
# Print the result
print("Paired t-test result:")
print(result)

Output:

> source("G:\\R\\prlab15.R")
[1] "Paired t-test result:"

Paired t-test

data: before and after


t = -3.2262, df = 19, p-value = 0.002223
alternative hypothesis: true mean difference is less than 0
99 percent confidence interval:
-Inf -0.2022072
sample estimates:
mean difference
-0.95

Exercise No.8(Part B)
Purpose: A company has three manufacturing plants, and company
officials want to determine whether there is difference in the average
age of workers at the three locations. The following data are the ages
of five randomly selected workers at each plant. Perform a one-way
ANOVA to determine whether there is a significant difference in the
mean ages of the workers at three plants. Use α=0.01. Write R script
for the above problem.
Plant(Employee Ages)
1 2 3
29 32 25
27 33 24
30 31 24
27 34 25
28 30 25

# Given data: ages of five randomly selected workers at each plant


plant1 <- c(29,27,30,27,28)
plant2 <- c(32,33,31,34,30)
plant3 <- c(25,24,24,25,25)

# Combine the data into a single data frame


data <- [Link](Plant = rep(c("Plant1", "Plant2", "Plant3"), each =
5),
Age = c(plant1, plant2, plant3))

# Perform one-way ANOVA


result <- aov(Age ~ Plant, data = data)

# Print ANOVA result


print(summary(result))

# Check if there is a significant difference


p_value <- summary(result)[[1]]$`Pr(>F)`[1]
alpha <- 0.01

if (p_value < alpha) {


print("There is a significant difference in the mean ages of workers
at the three plants.")
} else {
print("There is no significant difference in the mean ages of workers
at the three plants.")
}

Output:
> source("G:\\R\\prlab16.R")
Df Sum Sq Mean Sq F value Pr(>F)
Plant 2 136.9 68.47 45.64 2.46e-06 ***
Residuals 12 18.0 1.50
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
[1] "There is a significant difference in the mean ages of workers at
the three plants."
>

You might also like