0% found this document useful (0 votes)
485 views

5 Sem Lab Manual R Programming BCA-BSC

r programming lab

Uploaded by

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

5 Sem Lab Manual R Programming BCA-BSC

r programming lab

Uploaded by

manish.kh04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

F

SU
R Programming Lab Manual

U
Part A & B

YO
V Sem BCA / VI Sem BSC(CS)

Prepared by Muhammad Yousuf


AD
M
M
AM
H
U
M
R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 1

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

graphic functions: Plot(),Hist(),Linechart(),Pie(),Boxplot(),Scatterplots().


9. Write a R program for with any dataset containing dataframe objects, indexing and
subsetting
data frames, and employ manipulating and analyzing data.
10. Write a program to create an any application of Linear Regression in multivariate
H

context for predictive purpose.


_________________________________________________________________________________________
U

To run the program directly without downloading the r-studios/ r-software. Visit this
M

website https://www.mycompiler.io/new/r
_________________________________________________________________________________________

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 2

1. Write a R program for different types of data structures in 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"

# Data Frame [,1] [,2] [,3]


my_df <- data.frame(Name = c("Alice", "Bob", "Charlie"), [1,] 1 3 5
Age = c(25, 30, 22)) [2,] 2 4 6

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

[1] High Low Medium High


Low
Levels: High Low Medium
AM

Date Value
1 2023-01-01 100
2 2023-01-02 110
3 2023-01-03 105
H
U
M

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 3

2. Write a R program that include variables, constants, data types.

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")

cat("Character Vector:", char_vector, "\n")


cat("Integer Vector:", int_vector, "\n")
M

cat("Double Vector:", double_vector, "\n")


cat("Logical Vector:", logical_vector, "\n")
M
AM
H
U
M

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 4

3. Write a R program that include different operators, control structures,


default values for arguments, returning complex objects.

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

# Function with default argument values


calculate_area <- function(shape = "circle", radius = 1, length
Circle Area: 78.53982 for shape: circle
= 1, width = 1) {
if (shape == "circle") { Rectangle Area: 24 for shape: rectangle
area <- pi * radius^2 Default Area: 3.141593 for shape: circle
} else if (shape == "rectangle") { B

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()

# Print the results


cat("Circle Area:", circle_area$area, "for shape:",
circle_area$shape, "\n")
cat("Rectangle Area:", rect_area$area, "for shape:",
AD
rect_area$shape, "\n")
cat("Default Area:", default_area$area, "for shape:",
default_area$shape, "\n")

# Conditional statements
grade <- 85
M

if (grade >= 90) {


cat("A\n")
} else if (grade >= 80) {
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

is_warm <- TRUE

if (is_sunny && is_warm) {


cat("It's a nice day!\n")
}

# Complex objects (list of lists)


student1 <- list(name = "Alice", age = 25)
student2 <- list(name = "Bob", age = 22)
students <- list(student1, student2)

# Accessing complex object elements


cat("First student's name:", students[[1]]$name, "\n")
cat("Second student's age:", students[[2]]$age, "\n")

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 5

4. Write a R program for quick sort implementation, binary search tree.

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 Implementation: Binary Search Tree (BST) Implementation:

# 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] }

return(c(quick_sort(less), equal, if (key < root$key) {

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

bst_root <- insert(bst_root, 3)


bst_root <- insert(bst_root, 7)
bst_root <- insert(bst_root, 12)
bst_root <- insert(bst_root, 18)
M

cat("BINARY SEARCH TREE >>>In-order Traversal


(Sorted Order): ")
AM

inorder_traversal(bst_root)

Output :
H

QUICK SORT is in Sorted Array: 2 3 5 6 7 9 10 11 12 14


U

[Execution complete with exit code 0]

Output:
M

BINARY SEARCH TREE >>>In-order Traversal (Sorted Order): 3 5 7 10 12 15 18


[Execution complete with exit code 0]

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 6

5. Write a R program for calculating cumulative sums, and products minima


maxima and calculus.

In this program:

We calculate the cumulative sum and product of a vector.


We find the minimum and maximum values in the vector.
We perform basic calculus operations, including finding the derivative of a function and calculating the integral
of a function over a specified range. To use the Deriv and pracma libraries, you may need to install and load them
using install.packages and library functions.

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")

# Basic calculus operations


# Define a function
f <- function(x) {
AD
return(2 * x^2 + 3 * x + 1)
}

# Calculate the derivative (first order)


library(Deriv)
M

derivative <- Deriv(f, "x")


cat("Derivative of 2x^2 + 3x + 1:", derivative(2), "\n")

# Calculate the integral


M

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

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 7

6. Write a R program for finding stationary distribution of markanov


chains.

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:

# Load the markovchain package


library(markovchain)

# Define the transition matrix of the Markov chain


# Replace this with your own transition matrix
P <- matrix(c(0.7, 0.3, 0.2, 0.8), nrow = 2, byrow = TRUE)

# Create a markovchain object

F
mc <- new("markovchain", states = c("State1", "State2"), transitionMatrix = P)

# Find the stationary distribution

SU
stationary_distribution <- steadyStates(mc)

# Print the stationary distribution


cat("Stationary Distribution:")
print(stationary_distribution)

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

Stationary Distribution:> print(stationary_distribution)


State1 State2
[1,] 0.4 0.6
U
M

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 8

7. Write a R program that include linear algebra operations on vectors and


matrices.

In this program, we perform the following linear algebra operations:

Vector addition and subtraction.


Vector dot product.
Matrix addition and subtraction.
Matrix multiplication (using %*% for matrix multiplication).
Matrix determinant calculation.
Matrix inverse calculation (using solve).
You can run this code in an R environment to see the results of these linear algebra operations on vectors and
matrices.

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_diff <- matrix1 - matrix2


cat("Matrix Subtraction:\n")
print(matrix_diff)
Matrix Inverse:
[,1] [,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

matrix_inv <- solve(matrix1)


cat("Matrix Inverse:\n")
print(matrix_inv)
U
M

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 9

F
SU
U
YO
AD
M
M
AM
H
U
M

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 10

8. Write a R program for any visual representation of an object with creating


graphs using graphic functions:
Plot(),Hist(),Linechart(),Pie(),Boxplot(),Scatterplots().

# Create a sample dataset This program creates various


data <- c(23, 45, 56, 32, 67, 89, 55, 43, 78, 36, 49, 60, 70) types of graphs:

# Create a basic line chart A line chart using plot().


plot(data, type = "l", col = "blue", xlab = "X-axis", ylab = "Y-axis", main = "Line Chart") A histogram using hist().
A pie chart using pie().
# Create a histogram A box plot using boxplot().
hist(data, col = "lightblue", xlab = "Value", ylab = "Frequency", main = "Histogram") A scatterplot using plot() and
adds a regression line to it using
# Create a pie chart abline(). Finally, a legend is
pie_data <- c(20, 30, 40, 10) added to the scatterplot.
pie(pie_data, labels = c("A", "B", "C", "D"), col = rainbow(length(pie_data)), main = "Pie You can run this code in an R

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")

# Add a regression line to the scatterplot

YO
abline(lm(y ~ x), col = "blue")

# Create a legend for the scatterplot


legend("topleft", legend = "Regression Line", col = "blue", lty = 1)
AD
Output :
M
M
AM
H
U
M

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 11

9. Write a R program for with any dataset containing dataframe objects,


indexing and subsetting data frames, and employ manipulating and analyzing
data.

In this program:

We create a sample DataFrame called data.


We select specific columns from the DataFrame.
We subset rows based on a condition (age < 30).
We change a specific value in the DataFrame.
We add a new column (Salary) to the DataFrame.
We calculate the average age and maximum salary.
We use the dplyr library to group the data by the "City" column and calculate summary statistics for each group.
You can run this code in an R environment to manipulate and analyze the sample data in the DataFrame.

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

Maximum Salary: 70000


# Calculate the average age
average_age <- mean(data$Age) Attaching package: 'dplyr'
cat("Average Age:", average_age, "\n")
AM

The following objects are masked from


'package:stats':
# Calculate the maximum salary
filter, lag
max_salary <- max(data$Salary)
cat("Maximum Salary:", max_salary, "\n") The following objects are masked from
'package:base':
# Group data by a column and calculate summary statistics intersect, setdiff, setequal, union
library(dplyr)
H

[1] "Grouped Data:"


grouped_data <- data %>% # A tibble: 5 x 3
group_by(City) %>% City Average_Age Max_Salary
summarise(Average_Age = mean(Age), Max_Salary = max(Salary)) <chr> <dbl> <dbl>
U

print("Grouped Data:") 1 Chicago 28 65000


print(grouped_data) 2 Los Angeles 22 48000
3 Miami 35 70000
M

4 New York 26 55000


5 San Francisco 30 60000

[Execution complete with exit code 0]

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 12

10. Write a program to create an any application of Linear Regression in


multivariate context for predictive purpose.
Creating a linear regression model in a multivariate context involves predicting a dependent variable based on multiple independent
variables. Below is an example program in R that demonstrates how to build a multivariate linear regression model for predictive
purposes. In this example, I'll use the built-in "mtcars" dataset, which contains information about various car models.

# Load the mtcars dataset


data(mtcars)

# Explore the first few rows of the dataset


head(mtcars)

# Split the dataset into training and testing sets


set.seed(123) # Set seed for reproducibility
sample_index <- sample(1:nrow(mtcars), 0.7 * nrow(mtcars)) # 70% for training, 30% for testing

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

# Summary of the model


summary(model)

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

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 13

PART- B

Program1:r program for assigning values output


x<-3 assigned as local variable 3
cat("assigned as local variable",x ,"\n") assigned as global variable 3
x<<-3 assigned as local variable 3
cat("assigned as global variable",x,"\n") assigned as global variable 3
3->x
cat("assigned as local variable",x,"\n")
3->>x
cat("assigned as global variable",x,"\n")

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

Program4:R program by using explicit coerceion output


x<-c(2,3,4,5,6,7)
class(x) [1] "numeric"
print("converted to numerical coerceion") [1] "converted to numerical coerceion"
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

print("converted to logical coerceion") [1] "converted to logical coerceion"


as.logical(x) [1] TRUE TRUE TRUE TRUE TRUE TRUE
print("converted to list coerceion") [1] "converted to list coerceion"
as.list(x) [[1]]
print("converted to complex coerceion") [1] 2
as.complex(x)
H

[[2]]
[1] 3
U

[[3]]
[1] 4
M

[[4]]
[1] 5

[[5]]
[1] 6

[[6]]
[1] 7

[1] "converted to complex coerceion"


[1] 2+0i 3+0i 4+0i 5+0i 6+0i 7+0i

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 14

Program5: R program to create list with different Output


naming components
empId=c(1,2,3,4)
empName=c("kusuma","priya","radha","krishn") $Id
numberOfemp=4 [1] 1 2 3 4
empList=list(
"Id"=empId, $name
"name"=empName, [1] "kusuma" "priya" "radha" "krishn"
"total staff"=numberOfemp
) $t̀otal staff`
print(empList) [1] 4
Program6:r program to generate vectors using Output
Different functions and find its length
print("creating a numeric vector using a sequence")
my_vector<-1:10 [1] "creating a numeric vector using a sequence"
my_vector [1] 10
vector_length<-length(my_vector) [1] "creating a vector using the c() function"

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

break [1] "end of loop"


} [1] "prints the for loop using next statments"
print(x) [1] 2
} [1] 3
M

print("end of loop") [1] 4


[1] 6
print("prints the for loop using next statments") [1] 7
AM

for(x in c(2,3,4,0,6,7)) [1] "end of loop"


{
if(x==0)
{
next
}
H

print(x)
}
print("end of loop")
U

Program8:R program to use exception handling Output


result<-tryCatch({
x<-5/0 the operation is complete
M

},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);

# click on the source to execute this program

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR


R Programming Lab manual V Sem BCA / VI Sem BSC(Cs) 15

Program10: r program to execute using switch output


statement
nameofday=readline("which day is today:");
switch(nameofday,
"sunday"=cat("its the start of the week.\n"), which day is today: sunday
"saturday"=cat("its the weekend.\n"), its the start of the week
"default"=cat("its a regular day.\n")
)
# click on the source to execute this program

F
SU
U
YO
AD
M
M
AM
H
U
M

Prepared by MUHAMMAD YOUSUF, GFGC, CHIKKABALLAPUR

You might also like