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

R programming

The R Programming Lab Manual outlines a series of programming exercises designed to teach various statistical and data manipulation techniques using R. It includes tasks such as computing statistical measures, working with data types, performing linear algebra operations, visualizing data with graphs, and conducting linear regression analysis. Each lab provides sample code and explanations for implementing the specified tasks.

Uploaded by

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

R programming

The R Programming Lab Manual outlines a series of programming exercises designed to teach various statistical and data manipulation techniques using R. It includes tasks such as computing statistical measures, working with data types, performing linear algebra operations, visualizing data with graphs, and conducting linear regression analysis. Each lab provides sample code and explanations for implementing the specified tasks.

Uploaded by

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

R Programming Lab Manual VVFGC, Tumkur

Programs List:

1) Write a R-Program for to compute mean, median, minimum, maximum, variance, standard
deviation, skewness and quantities (Q1, Q2, Q3)
2) Write an R Program that includes variables, constants, and data types.
3) Write an R Program that include different operators, control structures, default values for
arguments, returning complex objects.
4) Write a R Program for calculating cumulative sums and products, minima, maxima
and calculus.
5) Write a R-Program for finding stationary distribution of markov chains.
6) Write a R Program that include linear algebra operations on vectors and matrices.
7) Write a R Program for any visual representation of an object with creating graphs using
graphic functions: Hist(), Linechart(), Pie()
8) Write a R Program for any visual representation of an object with creating graphs using
graphic functions: Plot(), Box plot(), Scatter plots()
9) Write R Program for any dataset containing data frame objects, indexing and subs
setting data frames and employ manipulating and analyzing data.
10) Write a Program to create any application of linear regression in multivariate context for
predictive purpose.

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 1


R Programming Lab Manual VVFGC, Tumkur

Lab-1:

Write a R-Program for to compute mean, median, minimum, maximum, variance,


standard deviation, skewness and quantities (Q1, Q2, Q3)
data<c(12,25,36,45,21,67,43,18,50,30) #sample data
mvalue<mean(data) #Computemean
mevalue<-median(data) #Compute median
minvalue<-min(data) #Compute minimum
maxvalue<-max(data) #Compute maximum
#Compute variance and standard deviation
varvalue<-var(data)
sdvalue<-sd(data)
#Compute skewness and kurtosis
skvalue<-skewness(data) #install moments package for this
kurtvalue<-kurtosis(data)
#Compute quantiles (Q1,Q2,Q3)
q1<-quantile(data,0.25)
q2<-quantile(data,0.50) #Same as median
q3<-quantile(data,0.75)
#Print the results
cat("Mean:",mvalue,"\n")
cat("Median:",mevalue,"\n")
cat("Minimum:",minvalue,"\n")
cat("Maximum:", maxvalue, "\n")
cat("Variance:",varvalue,"\n")
cat("StandardDeviation:",sdvalue,"\n")
cat("Skewness:",skvalue,"\n")
cat("Kurtosis:",kurtvalue,"\n")
cat("Q1:",q1,"\n")
cat("Q2(Median):",q2,"\n")
cat("Q3:",q3,"\n")

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 2


R Programming Lab Manual VVFGC, Tumkur

Lab-2:
Write an R Program that includes variables, constants, and data types.
# Constants
PI <- 3.14159
GREETING <- "Hello World!"
# Variables
age <- 30
name <- "Alice"
height <- 165.5
is_student<- TRUE
# Printing constants and variables
cat("Constants:\n")
cat("PI:", PI, "\n")
cat("GREETING:", GREETING, "\n\n")
cat("Variables:\n")
cat("Name:", name, "\n")
cat("Age:", age, "\n")
cat("Height:", height,"cm\n")
cat("Is Student:", is_student, "\n")
#Checking datatypes
cat("\n Data Types:\ n")
cat("Name is of type:", class(name), "\n")
cat("Age is of type:", class(age), "\n")
cat("Height is of type:", class(height), "\n")
cat("Is Student is of type:", class(is_student),"\n")

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 3


R Programming Lab Manual VVFGC, Tumkur

Lab-3:

Write an R Program that include different operators, control structures, default values for
arguments, returning complex objects

#Function with default argument values


calculate_area<-function(length=1,width=1)
{
area<-length*width
return(area)
}
calculate_area()

#Function that returns a complex object


create_person<-function(name,age,city)
{
person<-list(Name=name,Age=age,City=city)
return(person)
}

#Using different operators and control structures


length_value<-5
width_value<-3
area_result<-calculate_area(length_value,width_value)
cat("Area:",area_result,"\n")
#Controlstructure-if-else
if(area_result>10)
{
cat("This is a large area.\n")
}else
{

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 4


R Programming Lab Manual VVFGC, Tumkur
cat("This is a small area.\n")
}
#Using the function to create a person object
person1 <- create_person("Virat", 30, "India")
person2 <- create_person("Max Well",36,"Australia")
cat("Person1:\n")
cat("Name:",person1$Name, "\n")
cat("Age:",person1$Age,"\n")
cat("City:",person1$City,"\n")
cat("\nPerson2:\n")
cat("Name:",person2$Name, "\n")
cat("Age:",person2$Age,"\n")
cat("City:",person2$City,"\n")

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 5


R Programming Lab Manual VVFGC, Tumkur

Lab-4:

Write a R Program for calculating cumulative sums and products, minima, maxima and
calculus.

#Sample data set


data<-c(3,1,4,1,5,9,2,6,5,3)

#Cumulative sum cumulative_sum <-


cumsum(data) cat("CumulativeSum:\n")
cat(cumulative_sum,"\n\n")

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

#Minimum and Maximum


min_value<- min(data)
max_value<- max(data)
cat("MinimumValue:",min_value,"\n")
cat("MaximumValue:",max_value,"\n\n")
#Calculus
# Calculate the derivative of the data
derivative<-diff(data)
cat("Derivative of the Data:\n")
cat(derivative,"\n\n")
#Integrate the data
integral<-cumsum(derivative)
cat("Integral of the Data(Cumulative Sum of Derivative):\ n")
cat(integral,"\n")
Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 6
R Programming Lab Manual VVFGC, Tumkur

Lab-5:
Write a R-Program for finding stationary distribution of markov chains
library (Matrix)

# Transition probability matrix of the Markov chain


P <- matrix(c(0.4, 0.6, 0.2, 0.8), nrow = 2, byrow = TRUE)
print("probability matrix P is")
print(P)

# Check if the matrix P is stochastic (i.e., rows sum to 1)


if (all(rowSums(P) == 1))
{
eigen_result <- eigen(t(P)) # Transpose P and find eigenvalues/vectors
eigenvalues <- eigen_result$values
eigenvectors <- eigen_result$vectors

# Find the index of the eigenvalue that is closest to 1 (within a tolerance)


tol <- 1e-6
stationary_index <- which(abs(eigenvalues - 1) < tol)
if (length(stationary_index) == 0)
{
cat("No unique stationary distribution found.\n")
} else
{

stationary_distribution <- eigenvectors[, stationary_index] / sum(eigenvectors[,stationary_index])


cat("Stationary Distribution:", stationary_distribution, "\n")
}
} else
{
Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 7
R Programming Lab Manual VVFGC, Tumkur
cat("The transition matrix is not stochastic (rows should sum to 1).\n")
}

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 8


R Programming Lab Manual VVFGC, Tumkur

Lab-6:

Write a R Program that include linear algebra operations on vectors and matrices

#Create vectors
vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)

#Vector algebra
sum<- vec1 + vec2
diff <- vec1 - vec2
prod<- sum(vec1 * vec2)

#print result of vector algebra


cat("Vector Addition(vec1 + vec2):\n")
cat(sum, "\n\n")
cat("Vector Sub traction (vec1 - vec2):\n")
cat(diff , "\n\n")
cat("Vector Dot Product:\n")
cat(prod, "\n\n")

#Create matrices
mat1 <- matrix(1:6, nrow = 2,ncol=2,byrow=T)
print(mat1)

mat2 <- matrix(7:12, nrow = 2 ,ncol=2,byrow=T)


print(mat2)

#Matrix algebra
msum<- mat1 + mat2
msub<- mat1-mat2
mmul<- mat1 %*% mat2
Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 9
R Programming Lab Manual VVFGC, Tumkur

#print result of Matrix algebra


cat("Matrix Addition (mat1 + mat2):\ n")
print(msum)
cat("Matrix Subtraction (mat1 - mat2):\ n")
print(msub)
cat("Matrix multiplication (mat1 * mat2):\ n")
print(mmul)

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 10


R Programming Lab Manual VVFGC, Tumkur

Lab-7:

Write a R Program for any visual representation of an object with creating graphs
using graphic functions: Hist(), Linechart(), Pie()

Par(“mar”)

Par(mar=c(1,1,1,1))

#dev.off() is used to clear the plot area

#Sample data
data <- c(10, 15, 20, 25, 30, 35, 40, 45, 50, 55)
categories <- c("A", "B", "C", "D", "E")

#Create a histogram
hist(data, col = "green", main = "Histogram ", xlab = "Values", ylab = "Frequency")

# Create a line chart


time <- 1:10
values <- c(3, 5, 8, 10, 15, 20, 25, 30, 35, 40)
plot(time, values, type = "o", col = "red", xlab = "Time", ylab = "Values", main = "Line Chart ")

# Create a pie chart


percentages <- c(20, 30, 15, 10, 25) pie(percentages, labels = categories,
col = rainbow(length(categories)), main = "Pie Chart")

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 11


R Programming Lab Manual VVFGC, Tumkur

Lab-8:

Write a R Program for any visual representation of an object with creating graphs
using graphic functions: Plot(), Box plot(), Scatter plots()
x<-c(1,2,3,4,5)
y<-c(2,3,5,7,8)
#Create a scatter plot using plot()
plot(x,y,main="Scatter Plot using plot()",xlab="X-AxisLabel",ylab="Y-
AxisLabel",col="blue",pch=16)

# Create a box plot


#seed(arguments) is a random number generator set.seed(123)
db<-list(A=rnorm(50),B=rnorm(50),C=rnorm(50))
boxplot(db,col=rainbow(length(db)),main="BoxPlot")

#Create scatter plots


set.seed(456)
x<-rnorm(50)

y<-2*x+rnorm(50)
plot(x,y,col="blue",xlab="XValues",ylab="YValues",main="Scatterplot")
#dev.off()

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 12


R Programming Lab Manual VVFGC, Tumkur
Lab-9:

Write R Program for any dataset containing data frame objects, indexing and sub setting
data frames and employ manipulating and analyzing data.

#Create a sample data set as a data frame


data <-data.frame(Stdid=c(1,2,3,4,5),
Name= c("aaa","bbb","ccc", "ddd","eee"),
Age=c(25,30,22,28,24),
Score=c(95,87,75,92,88)
)
#Print the entire data frame
cat("Original Data Frame:\n")
print(data)

#Indexing and sub setting data frames


#Select rows where Age is greater than 25
subset<-data[data$Age>25, ]
cat("\n Subset of Data Frame(Age>25):\n")
print(subset)

#Select specific columns (Name and Score)


selectcol<-data[ , c("Name", "Score")]
cat("\n Selected Columns (Name and Score):\n")
print(selectcol)

#Calculate summary statistics


sumstat<-summary(data$Score)
cat("\nSummary Statistics for Score:\n")
cat(sumstat,"\n")

#Calculate the mean and standard deviation of Age


meanage<-mean(data$Age)

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 13


R Programming Lab Manual VVFGC, Tumkur
devage<- sd(data$Age)
cat("\n Mean Age:",meanage,"\n")
cat("Standard Deviation of Age:",devage,"\n")

#Calculate the correlation between Age and Score


corre<-cor(data$Age,data$Score)
cat("\n Correlation between Age and Score:",corre,"\n")

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 14


R Programming Lab Manual VVFGC, Tumkur
Lab-10:

Write a Program to create any application of linear regression in multivariate context for
predictive purpose.
T1<-c(15,17,8,19,20, 12, 13, 15, 15, 16)
T2<-c(13,15,15,16,15,17,10,19,20,13)
T3<-c(16,15,15, 16, 18, 17, 10, 19,20,11)
Finalexam<-c(70,65,65,75,85,50,40,90,87,60)
result<-1m(Finalexam~T1+T2+T3)
print(result)

cat("\n Predicted result is:\n")


presult<predict(result)
print(presult)

cat("\n Errored rate is:\n")


error<-residuals(result)
print(error)

cat("\n final result is:\n")


res<-data. frame (T1, T2, T3, Finalexam, presult, error)
print(res)

install.packages("car")
avplots (result)

#how to set the margins


#par("mar")
#par (mar=c(1,1,1,1))

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 15


R Programming Lab Manual VVFGC, Tumkur

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 16


R Programming Lab Manual VVFGC, Tumkur

Prepared By: K C Silpa, Asst. Professor. Dept. of BCA Page 17

You might also like