0% found this document useful (0 votes)
6 views31 pages

R Manual UP

The R-Programming Lab Manual for the University College of Science Tumakuru outlines a course for VI Semester BSc students, detailing a total of 52 contact hours and various assessments. It includes a comprehensive list of programming tasks covering data structures, statistical computations, operators, control structures, sorting algorithms, and calculus operations in R. The manual is authored by faculty member Spoorthi H A from the Department of Computer Science.

Uploaded by

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

R Manual UP

The R-Programming Lab Manual for the University College of Science Tumakuru outlines a course for VI Semester BSc students, detailing a total of 52 contact hours and various assessments. It includes a comprehensive list of programming tasks covering data structures, statistical computations, operators, control structures, sorting algorithms, and calculus operations in R. The manual is authored by faculty member Spoorthi H A from the Department of Computer Science.

Uploaded by

junaidpasha1997
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

R-Program Manual UCS,Tumakuru

UNIVERSITY COLLEGE OF SCIENCE TUMKURU-2024-25

R-PROGRAMMING LAB
MANUAL
COURSE: VI SEM BSc
SCHEME: NEP-2024-25

SUBMITTED BY FACULTY
SPOORTHI H A
DEPARTMENT OF COMPUTER SCIENCE

Spoorthi H A,Dept of CS Page 1


R-Program Manual UCS,Tumakuru

STATISTICAL & R-PROGRAMING

CourseTitle:R-PROGRAMMING LAB CourseCode:DSc9


TotalContactHours:52 Hours/Week:04
Formative Assessmentmarks:25 Course credits:02
Exam Marks:25 Duration of Exam:02Hours
By:SPOORTHI H A

LIST OF PROGRAMS
1. Write a R program for different types of data structures in R.
B)Write a R program to compute Mean,Median,Variance,Standard
Deviation,Min,Max, Skewness, Kurtosis and Quantiles(Q1, Q2, Q3)

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.


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.
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 graphic functions: Plot(),Hist(),Linechart(),Pie(),Boxplot(),Scatterplots().
9. Write a R program for with any dataset containing data frame objects, indexing and
sub setting data frames, and employ manipulating and analyzing data.
10. Write a program to create an any application of Linear Regression in multivariate
context for predictive purpose

Spoorthi H A,Dept of CS Page 2


R-Program Manual UCS,Tumakuru
1.A)Write a R program for different types of data structures in R.

#Vector
numeric_vector<-c(1,2,3,4, 5)
character_vector<-
c("apple","banana","cherry")
print(numeric_vector)
print(character_vector)

#Matrix
matrix_data<-matrix(1:9,nrow=3,ncol=3)
print(matrix_data)

#DataFrame
dataframe_data <-
data.frame(
Name=c("Amiya","Raj","A
sish"),
Language=c(“R”,“Python”,“
Java”), Age = c(22, 25, 45)
)
print(dataframe_data)

#List
my_list <- list(
numbers=c(1,2,3
),
names=c("John","Mary"),
matrix=matrix(1:6,nrow=2,ncol=3)
)
print(my_list)

#Factor
data<-
c("East","West","East","North","North","East","West","West","West",

Spoorthi H A,Dept of CS Page 3


R-Program Manual UCS,Tumakuru
"East", "North”)
factor_data<-factor(data)
print(factor_data)

OUTPUT
[1] 1 2 3 4 5
[1] "apple""banana""cherry"
[,1] [,2] [,3]
[1, 1 4 7
]
[2, 2 5 8
]
[3, 3 6 9
]
NameLangu
ageAge 1
Amiya R22
2RajPython25
3 Asish Java45
$numbers
[1] 1 2 3
$names
[1] "John""Mary"
$matri
x
[,1][,2]
[,3]
[1,]135
[2,]246
[1]EastWestEastNorthNorthEastWestWe
stWestEastNorth Levels:
East North West

B)Write a R program to compute Mean,Median,Variance,Standard

Spoorthi H A,Dept of CS Page 4


R-Program Manual UCS,Tumakuru
Deviation,Min,Max, Skewness, Kurtosis and Quantiles(Q1, Q2, Q3)

#Sampledata
xdata<-c(2,4.4,3,3,2,2.2,2,4)

#Compute Mean
mvalue<-
mean(xdata)
cat(“Mean:”,mvalue,“\n”)

#Compute Median
mevalue<-
median(xdata)
cat(“Median:”,mevalue,“\n”)

#ComputeMinimumandMaxi
mum minvalue<- min(xdata)
maxvalue<- max(xdata)
cat(“Minimum:”,minvalue,“\
n”)
cat(“Maximum:”,maxvalue,“\n”)

#ComputeVarianceandStandardDeviati
on varvalue<- var(xdata)
sdvalue<- sd(xdata)
cat(“Variance:”,varvalue,“\
n”)
cat(“StandardDeviation:”,sdvalue,“\n”)

#ComputeSkewnessandKurt
osis
#install.packages(“moments”
) #library(“moments”)
skvalue<-skewness(xdata)

Spoorthi H A,Dept of CS Page 5


R-Program Manual UCS,Tumakuru
kurtvalue<- kurtosis(xdata)
cat(“Skewness:”,skvalue,“\n
”)
cat(“Kurtosis:”,kurtvalue,“\n
”)

#ComputeQuantiles(Q1,Q
2,Q3) q1 <- quantile(xdata,
0.25)
q2<-
quantile(xdata,0.50)#Sameasmedian
q3 <- quantile(xdata, 0.75)
cat(“Q1:”,q1,“\n”)
cat(“Q2 (Median):”, q2,“\n”)
cat(“Q3:”,q3,“\n”)
OUTPU
T Mean:
2.825
Median: 2.6
Minimum: 2
Maximum:4.4
Variance:0.9078571
StandardDeviation:0.9528154
Skewness:0.637572
Kurtosis:1.902409
Q1: 2
Q2 (Median): 2.6
Q3: 3.25

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


#Variables
x <- 10 # Creating a numeric
variable name<-"Alice"#Creating a
character variable
Spoorthi H A,Dept of CS Page 6
R-Program Manual UCS,Tumakuru
is_student<-
TRUE#Creatingalogical(boolean)variable
print(x)
print(name)
print(is_student)

#Constants
PI<-3.14159265359#Definingaconstantfor PI
SPEED_OF_LIGHT<-
299792458#Definingaconstantforthespeedoflightinm/s Print(PI)
Print(SPEED_OF_LIGHT)

#DataTypes
#Numericdatatype
radius<-5.0#Numericvariable
area<-
PI*radius^2#Calculatingtheareaofacircle
print(area)

# Character data type


greeting<-
"Hello,World!"print(
greeting)

#Logical/Booleandatat
ype is_valid <- TRUE
print(is_valid)

#Listdatatype
person <- list(
name =
"Bob", age =
30,
is_student=TRUE
)

Spoorthi H A,Dept of CS Page 7


R-Program Manual UCS,Tumakuru
print(person)

#Complexdatat
ype a <- 9i + 3
print(a)
OUTPUT
[1] 10
[1] "Alice"
[1] TRUE
[1] 3.141593
[1] 299792458
[1] 78.53982
[1] "Hello,World!"
[1] TRUE
$name
[1] "Bob"
$age
[1] 30
$is_student
[1] TRUE
[1] 3+9i

Spoorthi H A,Dept of CS Page 8


R-Program Manual UCS,Tumakuru

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


structures, default values for arguments, returning complex objects.

#Operators
#ArithmeticOperators
a<-10
b<-3
addition <- a + b
subtraction <- a -
b
multiplication<-
a*b division <- a
/ b modulus <- a
%% b
exponential <- a
^b
print(addition)
print(subtraction)
print(multiplicati
on)
print(division)
print(modulus)
print(exponential)

#ComparisonOper
ators greater_than
<- a > b less_than
<- a < b equal_to
<- a == b
not_equal_to <- a
!= b
print(greater_than)
print(less_than)
print(equal_to)
Spoorthi H A,Dept of CS Page 9
R-Program Manual UCS,Tumakuru
print(not_equal_to)

# Logical Operators
logical_and<-
TRUE&&FALSE
logical_or <- TRUE ||
FALSE logical_not <-
!TRUE
print(logical_and)
print(logical_or)
print(logical_not)

#ControlStruct
ures if (a > b) {
result<-"aisgreaterthan b"
}else{
result<-"aisnotgreaterthanb"
}
print(result)
#Function with Default Argument Values
calculate_area<-
function(radius=1,pi=3.14159265359){ area <-
pi * radius^2
return(area)
}

area_default<-calculate_area()
area_custom<-
calculate_area(radius=5,pi=3.14)
print(area_default)
print(area_custom)

# Function Returning Complex Objects


create_person<-
function(name,age,is_student){ person <-

Spoorthi H A,Dept of CS Page 10


R-Program Manual UCS,Tumakuru
list(
Name=nam
e, Age =
age,
IsStudent=is_student
)
return(person)
}

person1<-
create_person("Alice",25,TRUE)
person2<-
create_person("Bob",30,FALSE)
print(person1)
print(person2)

Spoorthi H A,Dept of CS Page 11


R-Program Manual UCS,Tumakuru

OUTPUT
[1] 13
[1] 7
[1] 30
[1] 3.333333
[1] 1
[1] 1000
[1] TRUE
[1] FALSE
[1] FALSE
[1] TRUE
[1] FALSE
[1] TRUE
[1] FALSE
[2] "aisgreaterthanb"
[1] 3.141593
[1] 78.5
$Name
[1] "Alice"
$Age
[1] 25
$IsStudent
[1] TRUE
$Name
[1] "Bob"
$Age
[1] 30
$IsStudent
[1] FALSE

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

Spoorthi H A,Dept of CS Page 12


R-Program Manual UCS,Tumakuru

#QuickSort

quickSort<-function(arr){
random_index<-
sample(seq_along(arr),1); pivot <-
arr[random_index]
arr<-arr[-
random_index] left
<- c()
right<-c()
left<-
arr[which(arr<=pivot)]
right<-
arr[which(arr>pivot)]
if(length(left) > 1){
left<-quickSort(left)
}
if(length(right) >
1){ right<-
quickSort(right)
}
return(c(left,pivot,right))
}
arr<-
sample(1:100,10)
result <-
quickSort(arr)
print(result)

#BinarySearchTree

binarySearch=function(arr,
item){ low <- 1; high <-
length(arr)

Spoorthi H A,Dept of CS Page 13


R-Program Manual UCS,Tumakuru

while(low<=high){
mid<-
as.integer(round((low+high)/2))
if (abs(arr[mid] - item) ==0) {
return(mid)

}elseif(arr[mid]<ite
m){ low <- mid + 1
}else{
high<-mid-1
}
}
return(0)
}
arr<-c(4,0,3,1,5,6,2)
sorted_arr<-
sort(arr) item <-
4
cat("Array",arr,"\nSortedarray",sorted_arr,"\nitem=",item,
"\n") index <- binarySearch(sorted_arr, item)
if (index!=0){
cat("Element is present at index",index,"\n")
}else{
cat("element not found")
}
OUTPU
T
[1]1 14 41 42 53 55 75 89 92 93
Array4031562
Sortedarray0123456
item=4
Elementispresentatindex5

5.Write a R program for calculating cumulativesums, and products


minima maxima and calculus.

Spoorthi H A,Dept of CS Page 14


R-Program Manual UCS,Tumakuru

#Sampledata
data<-c(3,5,7,2,8)

# Cumulative Sum
cumulative_sum<-
cumsum(data)
cat("CumulativeSum:",cumulative_sum,"\n")

# Cumulative Product
cumulative_product <-
cumprod(data)
cat("CumulativeProduct:",cumulative_product,"\n")

# Minimum and
Maximum
minimum_value <-
min(data)
maximum_value<-
max(data)
cat("MinimumValue:",minimum_value,"\n")

cat("MaximumValue:",maximum_value,"\n")

#CalculusOperations
#Calculatethederivativeofafunction:f(x
)=x^2 f <- function(x) {
return(x^2)
}

#Derivati
ve x <- 2
h<-0.0001
derivative<-(f(x+h)-f(x))/h
cat("Derivativeatx=",x,"is",derivative,"\n")
Spoorthi H A,Dept of CS Page 15
R-Program Manual UCS,Tumakuru

#IntegrationusingRiemann
sums # Integrate f(x) from
1 to 4
integrate_function<-
function(f,a,b,n=1000){ dx <- (b - a) /
n
x <- seq(a, b, by =
dx) integral<-
sum(f(x)*dx)
return(integral)
}

a<-1
b<-4
integral_value <-integrate_function(f,a,b)
cat("Integraloff(x)from",a,"to",b,"is",integral_value,"\n")

OUTPU
T
CumulativeSum:3 81517 25
CumulativeProduct:3151052101680
Minimumvalue:2
Maximumvalue:8
Derivativeatx=2is4.0001
Integraloff(x)from1to4is21.0255

6.Write a R program for finding stationary distribution of mark anov


chains.

library(Matrix)

#TransitionprobabilitymatrixoftheMarkovchain
P<-matrix(c(0.4,0.6,0.2,0.8),nrow=2,byrow=TRUE)

Spoorthi H A,Dept of CS Page 16


R-Program Manual UCS,Tumakuru

#CheckifthematrixPisstochastic(i.e.,rowssu
mto1) if (all(rowSums(P) == 1)) {
eigen_result<-
eigen(t(P))#TransposePandfindeigenvalues/vectors
eigenvalues <- eigen_result$values
eigenvectors<-eigen_result$vectors

#Findtheindexoftheeigenvaluethatisclosestto1(withinatoler
ance) tol <- 1e-6
stationary_index<-which(abs(eigenvalues-1)<tol)

if(length(stationary_index)==0) {
cat("Nouniquestationarydistributionfound.\n")
}else{
stationary_distribution<-
eigenvectors[,stationary_index]/sum(eigenvectors[,
stationary_index])
cat("StationaryDistribution:",stationary_distribution,"\n")
}
}else{
cat("Thetransitionmatrixisnotstochastic(rowsshouldsumto1).\n")
}
OUTPU
T
StationaryDistribution:0.250.75

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


matrices.

#Definevectorsandmatri
ces v1 <- c(1, 2, 3)
v2<-c(4,5,6)
m1<-matrix(c(7,2,3,4),nrow=2,ncol=2)
m2<-matrix(c(9,8,7,6),nrow=2,ncol=2)

Spoorthi H A,Dept of CS Page 17


R-Program Manual UCS,Tumakuru

#Displayvectorsandmatrices
cat("Vector 1:", v1, "\n")
cat("Vector2:",v2,"\n
\n") cat("Matrix
1:\n") print(m1)
cat("\nMatrix2:\n
") print(m2)

# Linear algebra operations


cat("\nLinear Algebra
Operations:\n")

#VectorAddition
cat("VectorAddition:",v1+v2,"\n")

#VectorDotProduct
cat("VectorDotProduct:",sum(v1*v2),"\n")

# Matrix Addition
cat("\nMatrix
Addition:\n") print(m1
+ m2)

# Matrix Multiplication
cat("\nMatrix
Multiplication:\n")
print(m1 %*% m2)

# Transpose of a Matrix
cat("\nTransposeofMatrix
1:\n") print(t(m1))

#DeterminantofaMatrix
cat("\nDeterminantofMatrix1:",det(m1),"\n")

Spoorthi H A,Dept of CS Page 18


R-Program Manual UCS,Tumakuru

#InverseofaMatrix
cat("\nInverseofMatrix1:\n") inv_mat <-solve(m1) print(inv_mat)

OUTPUT
Vector1:123
Vector2:456
Matrix1:
[,1] [,2]
[1,]73
[2,]24
Matrix2:
[,1] [,2]
[1,]97
[2,]86
LinearAlgebraOperations: Vector Addition: 5 7 9 Vector Dot Product:
32 Matrix Addition
[,1] [,2]
[1,]1610
[2,]1010
MatrixMulti
plicatio
n: [,1]
[,2]
[1,]8767
[2,]5038
TransposeofMatrix 1:
[,1] [,2]
[1,]72
[2,]34
DeterminantofMatri
x1:22 Inverse of
Matrix 1:
[,1] [,2]
Spoorthi H A,Dept of CS Page 19
R-Program Manual UCS,Tumakuru

[1,]0.18181818 -0.1363636
[2,] -0.090909090.3181818

Spoorthi H A,Dept of CS Page 20


R-Program Manual UCS,Tumakuru

8.WriteaRprogramforanyvisualrepresentationofanobjectwithcreatinggrap
hsusinggraphic functions:
Plot(),Hist(),Linechart(),Pie(),Boxplot(),Scatterplots().

#Sampledata
data<-c(4,6,8,7,5,10,9,7,6,8)
categories<-
c("CategoryA","CategoryB","CategoryC","CategoryD","CategoryE")

#Histogram
hist(data,main="Histogram",xlab="Values",ylab="Frequency",col="lightblu
e")

#LineCha
rt x <-
1:5
y<-c(3,6,2,8,4)
plot(x,y,type="o",col="blue",main="LineChart",xlab="X-axis",ylab="Y-
axis")

#Pie Chart
slices<-c(10,20,15,30,25)
lbls<-categories
pie(slices,labels=lbls,main="PieChart")

#Box Plot
boxplot(data,horizontal=TRUE,main="BoxPlot",xlab="Values")

#ScatterPlot
x<-c(1,2,3,4,5,6,7,8,9,10)
y<-c(3,6,5,7,8,11,14,13,18,19)
plot(x,y,main="ScatterPlot",xlab="X-axis",ylab="Y-
axis",pch=16,col="red")

Spoorthi H A,Dept of CS Page 21


R-Program Manual UCS,Tumakuru

OUTPUT

Spoorthi H A,Dept of CS Page 22


R-Program Manual UCS,Tumakuru

Spoorthi H A,Dept of CS Page 23


R-Program Manual UCS,Tumakuru

Spoorthi H A,Dept of CS Page 24


R-Program Manual UCS,Tumakuru

9.WriteaRprogramforwithanydatasetcontainingdataframeobjects,indexing
andsubsetting data frames, and employ manipulating and analyzing data.

#CreateasampleDataFra
me data <- data.frame(
empname=c("Alice","Bob","Charlie","David"
,"Eve"), age = c(25, 30, 40, 28, 35),
n_projects=c(2,4,7,2,3),
designation=c("support","engineering","engineering","sales","sales")
)

#DisplaytheentireDataFrame
print(data)

#Indexing
name_column<-
data$empname
print("Name Column:")
print(name_column)

#Subsetting
young_employee<-
data[data$age<30,] print("Young
Employees:")
print(young_employee)

#Slicing
middle_employee<-
data[2:4,] print("Middle
Employees:")
print(middle_employee)

#Dicing

Spoorthi H A,Dept of CS Page 25


R-Program Manual UCS,Tumakuru

experienced_emp<-
data[data$n_projects>3&data$designation=="engineering",]
print(experienced_emp)

#Aggregation
average_age<-
mean(data$age)
print(average_age)
average_projects <- mean(data$n_projects)
print(average_projects)

#DataAnalysis

Spoorthi H A,Dept of CS Page 26


R-Program Manual UCS,Tumakuru

# Find the employees with the highest number of


projects max_projects_employee<-
data[which.max(data$n_projects),]
print("Employee with the Highest Number of
Projects:") print(max_projects_employee)
OUTPU
T
empnameagen_projectsdesignations
1 Alice25 2 support
2 Bob30 4engineering
3 Charlie40 7engineering
4 David28 2 sales
5 Eve35 3 sales
[1] "Name Column:"
[3] "Alice""Bob" "Charlie""David""Eve"
[1] "Young

Employees:"
empnameagen_projects
designations
1Alice25 2 support
4David28 2 sales
[1] "Middle
Employees:"
empnameagen_projects
designations
2 Bob30 4engineering
3 Charlie40 7engineering
4David28 2 sales
empnameagen_projects
designations
2 Bob30 4engineering
3 Charlie40 7engineering
[1] 31.6
[1] 3.6
[1]"Employeewiththehighestnumberof
projects:" empname age

Spoorthi H A,Dept of CS Page 27


R-Program Manual UCS,Tumakuru
n_projects designations
3 Charlie40 7engineering

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


multi variate context for predictive purpose

Imarks=c(10,15,17,10,18,20,5,13,15,12)
Emarks=c(70,80,90,50,85,90,30,60,70,70)
LReg=lm(Emarks~I
marks) LReg
PredicatedResult =
predict(LReg)
PredicatedResult
Error=residuals(L
Reg) Error
Result=data.frame(Imarks,Emarks,PredicatedRe
sult,Error) Result

plot(Imarks,Emarks,col="red",main="InternalandExternalmarksRegression",
abline(lm(Emarks~Imarks)))
a<-
data.frame(Imarks=10)
result <- predict(LReg,
a) result

Spoorthi H A,Dept of CS Page 28


R-Program Manual UCS,Tumakuru
OUTPU
T
Call:
lm(formula=Emar
ks~Imarks)
Coefficients:
(Intercept)
Ima
rks16.748
3.90
8
>PredicatedResult
1 2 3 4 5 6 7 8 9 10
55.82353 75.36134 83.17647 55.82353 87.08403 94.89916 36.28571
67.54622 75.36134 63.63866
>Error
1 2 3 4 5 6 7 8 9
14.1764714.6386556.823529 -5.823529 -2.084034 -4.899160 -6.285714
-7.546218 -5.361345
10
6.36134
5
>Result
ImarksEmarks PredicatedResult Error
1 10 70 55.82353 14.176471
2 15 80 75.361344.638655
3 17 90 83.176476.823529
4 10 50 55.82353 -5.823529
5 18 85 87.08403 -2.084034
6 20 90 94.89916 -4.899160
7 5 30 36.28571 -6.285714
8 13 60 67.54622 -7.546218
9 15 70 75.36134 -5.361345
10 12 70 63.638666.361345
>result
1
55.82353

Spoorthi H A,Dept of CS Page 29


R-Program Manual UCS,Tumakuru

Spoorthi H A,Dept of CS Page 30


R-Program Manual UCS,Tumakuru

Spoorthi H A,Dept of CS Page 31

You might also like