5 Sem Lab Manual R Programming BCA-BSC
5 Sem Lab Manual R Programming BCA-BSC
SU
R Programming Lab Manual
U
Part A & B
YO
V Sem BCA / VI Sem BSC(CS)
F
SU
U
YO
1. Write a R program for different types of data structures in R.
AD
2. Write a R program that include variables, constants, data types.
3. Write a R program that include different operators, control structures, default values for
arguments, returning complex objects.
4. Write a R program for quick sort implementation, binary search tree.
M
5. Write a R program for calculating cumulative sums, and products minima maxima and
calculus.
6. Write a R program for finding stationary distribution of markanov chains.
M
7. Write a R program that include linear algebra operations on vectors and matrices.
8. Write a R program for any visual representation of an object with creating graphs using
AM
To run the program directly without downloading the r-studios/ r-software. Visit this
M
website https://www.mycompiler.io/new/r
_________________________________________________________________________________________
You can run this code in an R environment to see how these data structures work. Each data structure has
its own use cases and properties, and you can perform various operations on them to manipulate and
analyze data.
Program Output
# Vector [1] 1 2 3 4 5
my_vector <- c(1, 2, 3, 4, 5) $name
print(my_vector) [1] "John"
# List
my_list <- list(name = "John", age = 30, city = "New York")
$age
print(my_list)
[1] 30
F
# Matrix
my_matrix <- matrix(1:6, nrow = 2, ncol = 3) $city
SU
print(my_matrix) [1] "New York"
U
print(my_df) Name Age
1 Alice 25
# Array
YO
2 Bob 30
my_array <- array(1:12, dim = c(2, 3, 2))
3 Charlie 22
print(my_array)
,,1
# Factor
my_factor <- factor(c("High", "Low", "Medium", "High", "Low")) [,1] [,2] [,3]
print(my_factor) [1,] 1 3 5
AD
[2,] 2 4 6
# DataFrame with time-series
date <- as.Date(c("2023-01-01", "2023-01-02", "2023-01-03")) ,,2
value <- c(100, 110, 105)
df_time_series <- data.frame(Date = date, Value = value) [,1] [,2] [,3]
M
print(df_time_series)
[1,] 7 9 11
[2,] 8 10 12
M
Date Value
1 2023-01-01 100
2 2023-01-02 110
3 2023-01-03 105
H
U
M
In this program, we define variables (e.g., name, age, height, is_student) and constants (e.g., PI, G). We also
demonstrate different data types such as character vectors, integer vectors, double vectors, and logical
vectors. The cat function is used to print the values of these variables, constants, and data types.
Program output
Name: Alice
# Variables
Age: 25
name <- "Alice"
Height: 165.5
age <- 25
Is Student: TRUE
height <- 165.5
PI Constant: 3.141593
is_student <- TRUE
Gravity Constant: 9.81
F
Character Vector: apple banana cherry
# Constants
Integer Vector: 1 2 3 4 5
PI <- 3.14159265359
SU
Double Vector: 1.5 2.7 3
G <- 9.81
Logical Vector: TRUE FALSE TRUE FALSE
# Data Types
[Execution complete with exit code 0]
char_vector <- c("apple", "banana", "cherry")
int_vector <- c(1, 2, 3, 4, 5)
U
double_vector <- c(1.5, 2.7, 3.0)
logical_vector <- c(TRUE, FALSE, TRUE, FALSE)
YO
# Print variables, constants, and data types
cat("Name:", name, "\n")
cat("Age:", age, "\n")
cat("Height:", height, "\n")
cat("Is Student:", is_student, "\n")
AD
cat("PI Constant:", PI, "\n")
cat("Gravity Constant:", G, "\n")
This program defines a function calculate_area with default argument values and returns a complex object (a list). It
also includes control structures (if-else statements and a for loop), logical operators, and demonstrates working
with complex objects (lists of lists).
program Output
F
area <- length * width Iteration: 1
} else {
Iteration: 2
SU
area <- 0
} Iteration: 3
return(list(shape = shape, area = area)) Iteration: 4
} Iteration: 5
It's a nice day!
U
# Calculate areas using the function
circle_area <- calculate_area("circle", radius = 5)
rect_area <- calculate_area("rectangle", length = 4, width = 6) [Execution complete with exit code 0]
YO
default_area <- calculate_area()
# Conditional statements
grade <- 85
M
cat("B\n")
} else if (grade >= 70) {
cat("C\n")
AM
} else {
cat("F\n")
}
# Loop
for (i in 1:5) {
H
cat("Iteration:", i, "\n")
}
U
# Logical operators
is_sunny <- TRUE
M
The first part of the code implements the Quick Sort algorithm, and the second part implements a Binary Search
Tree (BST) with insertion and in-order traversal to print elements in sorted order. You can modify and extend
these implementations as needed.
# Quick Sort function # Define a Node structure for the Binary Search Tree
quick_sort <- function(arr) { Node <- function(key) {
if (length(arr) <= 1) { return(list(key = key, left = NULL, right = NULL))
return(arr) }
}
# Insert a value into the BST
pivot <- arr[1] insert <- function(root, key) {
less <- arr[arr < pivot] if (is.null(root)) {
equal <- arr[arr == pivot] return(Node(key))
F
greater <- arr[arr > pivot] }
SU
quick_sort(greater))) root$left <- insert(root$left, key)
} } else if (key > root$key) {
root$right <- insert(root$right, key)
# Example usage }
unsorted_array <- c(9, 7, 5, 11, 12, 2, 14, 3, 10, 6)
U
sorted_array <- quick_sort(unsorted_array) return(root)
cat("QUICK SORT is in Sorted Array :", }
sorted_array, "\n")
# In-order traversal to print BST elements in sorted order
YO
inorder_traversal <- function(root) {
if (!is.null(root)) {
inorder_traversal(root$left)
cat(root$key, " ")
inorder_traversal(root$right)
}
}
AD
# Example usage
bst_root <- NULL
bst_root <- insert(bst_root, 10)
bst_root <- insert(bst_root, 5)
bst_root <- insert(bst_root, 15)
M
inorder_traversal(bst_root)
Output :
H
Output:
M
In this program:
Program Output
# Create a sample vector Cumulative Sum: 1 3 6 10 15
values <- c(1, 2, 3, 4, 5) Cumulative Product: 1 2 6 24 120
F
Minimum Value: 1
# Calculate cumulative sum
cumulative_sum <- cumsum(values) Maximum Value: 5
SU
cat("Cumulative Sum:", cumulative_sum, "\n") Error in library(Deriv) : there is no
package called 'Deriv'
# Calculate cumulative product Execution halted
cumulative_product <- cumprod(values)
cat("Cumulative Product:", cumulative_product, "\n")
[Execution complete with exit code
U
# Find the minimum and maximum values 1]
min_value <- min(values)
YO
max_value <- max(values)
cat("Minimum Value:", min_value, "\n")
cat("Maximum Value:", max_value, "\n")
library(pracma)
integral <- integral(f, lower = 1, upper = 2)
cat("Integral of 2x^2 + 3x + 1 from 1 to 2:", integral, "\n")
AM
H
U
M
Finding the stationary distribution of a Markov chain typically involves solving a set of linear equations. You can use
the markovchain and solve functions in R to find the stationary distribution.
Here's an example R program:
F
mc <- new("markovchain", states = c("State1", "State2"), transitionMatrix = P)
SU
stationary_distribution <- steadyStates(mc)
U
Note: Make sure you have an active internet connection, as this command will download the package from the
YO
Comprehensive R Archive Network (CRAN) and install it on your machine.
First Dowload & install R packages, you can use the install.packages("markovchain") function.
Second download & install the "markovchain" package in R. Here's how you can install the "markovchain" package you can
use the install.packages("markovchain") function
AD
Third : After the installation is complete, you can load the package into your R session using the library(markovchain)
function
Keep in mind that you only need to install a package once, but you'll need to load it in each new R session where you want
to use its functions.
M
Define the transition matrix P of your Markov chain. Make sure it represents the transitions between your states
M
correctly.
Create a markovchain object with the transition matrix.
Use the steadyStates function to find the stationary distribution.
Print the stationary distribution.
AM
Make sure to replace the example transition matrix with your own transition matrix based on your specific Markov
chain.
Output :
H
Program output
# Create vectors
F
vector1 <- c(1, 2, 3)
vector2 <- c(4, 5, 6) Vector Addition: 5 7 9
SU
# Create matrices
matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2) Vector Subtraction: -3 -3 -3
matrix2 <- matrix(c(7, 8, 9, 10), nrow = 2) Vector Dot Product: 32
# Vector addition Matrix Addition:
vector_sum <- vector1 + vector2 [,1] [,2]
U
cat("Vector Addition:", vector_sum, "\n")
[1,] 8 12
# Vector subtraction [2,] 10 14
YO
vector_diff <- vector1 - vector2
cat("Vector Subtraction:", vector_diff, "\n") Matrix Subtraction:
[,1] [,2]
# Vector dot product
dot_product <- sum(vector1 * vector2) [1,] -6 -6
cat("Vector Dot Product:", dot_product, "\n") [2,] -6 -6
Matrix Multiplication:
AD
# Matrix addition
matrix_sum <- matrix1 + matrix2
cat("Matrix Addition:\n")
[,1] [,2]
print(matrix_sum) [1,] 34 38
# Matrix subtraction
[2,] 50 56
Matrix Determinant: -2
M
# Matrix multiplication
matrix_product <- matrix1 %*% t(matrix2)
[1,] -2 1.5
cat("Matrix Multiplication:\n") [2,] 1 -0.5
print(matrix_product)
AM
# Matrix determinant
matrix_det <- det(matrix1)
cat("Matrix Determinant:", matrix_det, "\n")
# Matrix inverse
H
F
SU
U
YO
AD
M
M
AM
H
U
M
F
Chart") environment to visualize the
different graph types.
SU
# Create a boxplot
boxplot(data, col = "lightgreen", xlab = "Value", main = "Box Plot")
# Create a scatterplot
x <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
y <- c(2, 4, 5, 7, 8, 10, 11, 14, 15, 17)
U
plot(x, y, col = "red", xlab = "X-axis", ylab = "Y-axis", main = "Scatterplot")
YO
abline(lm(y ~ x), col = "blue")
In this program:
F
Program output
SU
# Create a sample DataFrame
data <- data.frame( Name Age City
Name = c("Alice", "Bob", "Charlie", "David", "Eve"), 1 Alice 25 New York
Age = c(25, 30, 22, 28, 35), 2 Bob 30 San Francisco
City = c("New York", "San Francisco", "Los Angeles", "Chicago", "Miami") 3 Charlie 22 Los Angeles
) 4 David 28 Chicago
U
5 Eve 35 Miami
# Display the entire DataFrame [1] "Selected Columns:"
print(data) Name Age
1 Alice 25
YO
2 Bob 30
# Select specific columns
3 Charlie 22
selected_columns <- data[c("Name", "Age")]
4 David 28
print("Selected Columns:") 5 Eve 35
print(selected_columns) [1] "Young People:"
# Select rows based on a condition Name Age City
young_people <- data[data$Age < 30, ] 1 Alice 25 New York
AD
print("Young People:") 3 Charlie 22 Los Angeles
print(young_people) 4 David 28 Chicago
[1] "DataFrame with Salary:"
# Change a specific value in the DataFrame Name Age City Salary
data[1, "Age"] <- 26 1 Alice 26 New York 55000
2 Bob 30 San Francisco 60000
# Add a new column to the DataFrame 3 Charlie 22 Los Angeles 48000
M
data$Salary <- c(55000, 60000, 48000, 65000, 70000) 4 David 28 Chicago 65000
print("DataFrame with Salary:") 5 Eve 35 Miami 70000
print(data) Average Age: 28.2
M
F
train_data <- mtcars[sample_index, ]
test_data <- mtcars[-sample_index, ]
SU
# Build a multivariate linear regression model
model <- lm(mpg ~., data = train_data) # Assuming "mpg" is the dependent variable
U
# Make predictions on the test set
predictions <- predict(model, newdata = test_data)
YO
# Evaluate the model
mse <- mean((predictions - test_data$mpg)^2) # Mean Squared Error
# Print the Mean Squared Error
cat("Mean Squared Error:", mse, "\n")
This example uses the "mpg" (miles per gallon) variable as the dependent variable and includes all other variables in the dataset as
AD
independent variables. You may need to adjust the code based on your specific dataset and the variable you want to predict.
OUTPUT:
M
M
AM
H
U
M
PART- B
F
Program2:r program by using different vector output
SU
functions
x<-c(2,3,4,5,6,7)
cat('using c functon',x,'\n') using c functon 2 3 4 5 6 7
#using c function 2,3,4,5,6,7
z<-2:9 using colon 2 3 4 5 6 7 8 9
U
cat('using colon',z) using se() function 1 3.25 5.5 7.75 10
y<- seq(1,10,length.out=5) [1] 5
cat('using se() function',y,'\n')
YO
length(y)
Program3: R program to create movie as class name output
movieList<-list(name="master",leaderActor="priya")
class(movieList)<-"movie" $name
print(movieList) [1] "master"
$leaderActor
AD
[1] "priya"
attr(,"class")
[1] "movie"
M
as.numeric(x) [1] 2 3 4 5 6 7
print("converted to double coerceion") [1] "converted to double coerceion"
as.double(x) [1] 2 3 4 5 6 7
AM
[[2]]
[1] 3
U
[[3]]
[1] 4
M
[[4]]
[1] 5
[[5]]
[1] 6
[[6]]
[1] 7
F
vector_length [1] 2 3 4 5 6
print("creating a vector using the c() function") [1] 5
SU
my_vector<-c(2,3,4,5,6) [1] "creating a numeric vector using rep()
my_vector function"
vector_length<-length(my_vector) [1] 5 5 5
vector_length [1] 3
print("creating a numeric vector using rep() function") [1] "creating a numeric vector using vectorized
U
my_vector<-rep(5,times=3) operations"
my_vector [1] 2 4 6 8 10
vector_length<-length(my_vector)
YO
vector_length
print("creating a numeric vector using vectorized
operations")
v1<-1:5
v2<-v1*2
v2
Program7: R program to create a simple for loop Output
AD
print("prints the for loop using break statments")
for(x in c(2,3,4,0,6,7)) [1] "prints the for loop using break statments"
{ [1] 2
if(x==0) [1] 3
{ [1] 4
M
print(x)
}
print("end of loop")
U
},error=function(err)
{
cat("error:",conditionMessage(err),"\n")
},finally={
cat("the operation is complete\n")
})
Program9:r program to access user input from console output
name=readline("enter your name:"); enter your name:Md
name=readline(prompt="enter last name"); enter last name Yousuf
age=readline("enter your age:"); enter your age:25
age=as.integer(age); [1] "Md Yousuf"
print(name); [1] 25
print(age);
F
SU
U
YO
AD
M
M
AM
H
U
M