Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Part a r Programming

The document outlines a series of R programming tasks including matrix operations, quadratic equation solving, prime number generation, list manipulations, histogram and frequency polygon creation, data frame operations, factor manipulations, and operations on the Iris dataset. Each task includes code snippets and explanations for performing specific operations in R. The tasks are designed to demonstrate various programming concepts and data analysis techniques using R.

Uploaded by

farisfari313e
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Part a r Programming

The document outlines a series of R programming tasks including matrix operations, quadratic equation solving, prime number generation, list manipulations, histogram and frequency polygon creation, data frame operations, factor manipulations, and operations on the Iris dataset. Each task includes code snippets and explanations for performing specific operations in R. The tasks are designed to demonstrate various programming concepts and data analysis techniques using R.

Uploaded by

farisfari313e
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

R- Program Lab

Part A
1) Write a program to create a 3 X 3 matrices A and B and perform the following operations
a. AT.B
b. BT.(A.AT)
c. (A.AT).BT
d. [(B.BT)+(A.AT)-100I3]-1
# Create matrices A and B
A <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3)
B <- matrix(c(9, 8, 7, 6, 5, 4, 3, 2, 1), nrow = 3)

# Calculate AT.B
result_a <- t(A) %*% B

# Calculate BT.(A.AT)
result_b <- t(B) %*% (A %*% t(A))

# Calculate (A.AT).BT
result_c <- (A %*% t(A)) %*% B

# Calculate [(B.BT) + (A.AT) - 100*diag(3)]^(-1)


result_d <- solve((B %*% t(B)) + (A %*% t(A)) - 100 * diag(3))

# Print results
print("Result of AT.B:")
print(result_a)

print("Result of BT.(A.AT):")
print(result_b)

print("Result of (A.AT).BT:")
print(result_c)

print("Result of [(B.BT) + (A.AT) - 100*diag(3)]^(-1):")


print(result_d)
2) Write R program to find roots of quadratic equation using user defined function. Test the program
user supplied values for all possible cases.

# Define the quadratic equation function


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

# Check if the discriminant is positive, negative, or zero


if (d > 0) {
# The equation has two real roots
x1 <- (-b + sqrt(d)) / (2 * a)
x2 <- (-b - sqrt(d)) / (2 * a)

# Print the roots


print(paste("/n The roots of the equation are:", x1, "and", x2))
} else if (d == 0) {
# The equation has one real root
x <- -b / (2 * a)

# Print the root


print(paste("/n The root of the equation is:", x))
} else {
# The equation has no real roots
print("/n The equation has no real roots.")
}
}
# Test the function with user-supplied values
a <- as.numeric(readline("Enter the value of a: "))
b <- as.numeric(readline("Enter the value of b: "))
c <- as.numeric(readline("Enter the value of c: "))
# Call the function
quadratic_equation(a, b, c)
3) Write R script to generate prime numbers between two numbers using loops

generate_primes <- function(start, end) {


prime_numbers <- vector("numeric", 0)
for (i in start:end) {
is_prime <- TRUE
for (j in 2:sqrt(i)) {
if (i %% j == 0) {
is_prime <- FALSE
break
}
}
if (is_prime) {
prime_numbers <- c(prime_numbers, i)
}
}
return(prime_numbers)
}

start <- as.numeric(readline("Enter the starting number: "))


end <- as.numeric(readline("Enter the ending number: "))

prime_numbers <- generate_primes(start, end)

cat("Prime numbers between", start, "and", end, "are:\n",prime_numbers)

print(paste("The prime numbers between", start, "and", end, "are:", prime_numbers))


4) Write an 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 containing strings, numbers, vectors and logical values


my_list <- list("hello", 123, c(1, 2, 3), TRUE)

# Access the first element in the list


first_element <- my_list[[1]]
print(first_element)

# Give names to the elements in the list


names(my_list) <- c("string", "number", "vector", "logical")

# Add element at some position in the list


my_list <- append(my_list, "new element", after = 2)
print(my_list)

# Remove the element


my_list <- my_list[-3]
print(my_list)

# Print the first and third element


first_element <- my_list[[1]]
third_element <- my_list[[3]]

print(first_element)
print(third_element)

# Update the third element


my_list[[3]] <- c(4, 5, 6)
print(my_list)
5) The following table shows the time taken (in minutes) by 100 students to travel to school on
a particular day.

Time 0-5 5-10 10-15 15-20 20-25


Number of Students 5 25 40 17 13

a. Draw the histogram


b. Draw frequency polygon

vi=c(0,5,10,15,20)
vi2=c(5,10,15,20,25)
y_data=(vi+vi2)/2
freq=c(5,25,40,17,13)

Cumulative_Freq <- cumsum(freq)

hist_data <- rep(y_data,freq)


hist_breaks <- c(0, 5, 10, 15, 20, 25) # Define breaks
hist_freq <- hist(hist_data, breaks = hist_breaks, plot = FALSE)

# Plot the histogram


hist(hist_data,
breaks = hist_breaks,
main = "Histogram of Time Taken to Travel to School",
xlab = "Time (minutes)", ylab = "Frequency")

ItemCode itemCategory ItemPrice plot(0, 0, type =


1001 Electronics 700 "n", xlim = c(0,
1002 Desktop Supplies 300 25), ylim = c(0,
1003 Office Supplies 350
1004 USB 400
1005 CD Drive 800
max(Cumulative_Freq)),
xlab = "Time Taken (minutes)", ylab = "Cumulative Frequency",
main = "Frequency Polygon")

points(y_data, Cumulative_Freq, pch = 20, col = "blue")


polygon(y_data, Cumulative_Freq, col = "blue")

# Add class interval labels


text(y_data, Cumulative_Freq, labels = y_data, pos = 3)

6) Write an R program to create a Data Frame with following details and do the following
operations.

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.

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

subset_a<-data[data$ItemPrice>=350,]

subset_b<-data[data$itemCategory%in%c("Office Supplies","Desktop Supplies"),]

subset_c<-data[data$ItemPrice>=300&data$ItemPrice<=700,]

total_price<-sum(data$ItemPrice)

item_details<-data.frame(
itemCode=c(1001,1002,1003,1004,1005),
ItemQtyonHand=c(10,15,20,5,12),
ItemReorderLvl=c(2,5,3,4,6)
)
merge_data<-merge(data,item_details,by="itemCode")

print("a. subset grater than = 350")


print(subset_a)

print("b. subset item is office or desktop")


print(subset_b)

print("c. between 300 and 700")


print(subset_c)

print("d. sum of the item")


print(total_price)

print("e. Merge data")


print(merge_data)
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. Modify the second element of the factor
e. Add new level widowed to the factor and add the same level to the factor
marital_status

#create the factor


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

#is.factor
isfactors<-is.factor(marital_status)
print(isfactors)

#Access the 2nd and 4th element in the factor


marital_status[c(2, 4)]

#Remove the third element from the factor


marital_status<-marital_status[-3]
print(marital_status)

# Modify the second element of the factor


marital_status[2]<-"divorced"
print(marital_status)

#Add new level widowed to the factor and add the same level to the factor marital_status
factor(append(as.character(marital_status),"Widowed"))

8) Write a 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 Sepal.Length and Petal.Length
10. Create correlation matrix for dataset
# Load the Iris dataset
data(iris)

# View the first six rows of the Iris dataset


head(iris)
# Summarize the Iris dataset
summary(iris)

# Display the number of rows and columns


dim(iris)

# Display column names


colnames(iris)

# Create a histogram of sepal length


hist(iris$Sepal.Length, main = "Histogram of Sepal Length", xlab = "Sepal Length")

# Create a scatterplot of sepal width vs. sepal length


plot(iris$Sepal.Length, iris$Sepal.Width, main = "Scatterplot of Sepal Width vs. Sepal Length", xlab
= "Sepal Length", ylab = "Sepal Width")

# Create a boxplot of sepal width vs. sepal length


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

# Find Pearson correlation between Sepal.Length and Petal.Length


cor(iris$Sepal.Length, iris$Petal.Length, method = "pearson")

# Create a correlation matrix for the dataset


cor_matrix <- cor(iris[, 1:4])
cor_matrix

You might also like