0% found this document useful (0 votes)
20 views21 pages

R Lab Manual

Uploaded by

evillord384
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)
20 views21 pages

R Lab Manual

Uploaded by

evillord384
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/ 21

R programming lab

PART A:
1.Write a R program for different types of data structures in R
print("Vectors")
X = c(1, 3, 5, 7, 8)
print(X)
print("List")
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4
empList = list(empId, empName, numberOfEmp)
print(empList)
print("DataFrames")
Name = c("Amiya", "Raj", "Asish")
Language = c("R", "Python", "Java")
Age = c(22, 25, 45)
df = data.frame(Name, Language, Age)
print(df)
print("Matrix")
A = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3, ncol = 3,
byrow = TRUE)
print(A)
print("Array")
A = array(c(1, 2, 3, 4, 5, 6, 7, 8),
dim = c(2, 2, 2) )
print(A)
print("factors")
fac = factor(c("Male", "Female", "Male",
"Male", "Female", "Male", "Female"))
print(fac)

BIHE Davangere Page 1


R programming lab

Output:
"Vectors"

[1] 1 3 5 7 8

"List"
[[1]]
[1] 1 2 3 4

[[2]]
[1] "Debi" "Sandeep" "Subham" "Shiba"

[[3]]
[1] 4

"DataFrames"

Name Language Age


1 Amiya R 22
2 Raj Python 25
3 Asish Java 45

"Matrix"
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9

"Array"
,,1

[,1] [,2]
[1,] 1 3
[2,] 2 4

,,2

[,1] [,2]
[1,] 5 7
[2,] 6 8

"factors"
[1] Male Female Male Male Female Male Female
Levels: Female Male

BIHE Davangere Page 2


R programming lab

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

a = TRUE
print(a)
print(class(a))

A = 14L
print(A)
print(class(A))

x = 13.4
print(x)
print(class(x))

alphabet = "a"
print(alphabet)
print(class(alphabet))

message = "Welcome to Programiz!"


print(message)
print(class(message))

Output:
[1] TRUE
[1] "logical"
[1] 14
[1] "integer"
[1] 13.4
[1] "numeric"
[1] "a"
[1] "character"
[1] "Welcome to Programiz!"
[1] "character"

3.Write a R program that include different operators, control structures, default values for
arguments, returning complex objects
a. operators
vec1 <- c(0, 2)
vec2 <- c(2, 3)

cat ("Addition of vectors :", vec1 + vec2, "\n")


cat ("Subtraction of vectors :", vec1 - vec2, "\n")
cat ("Multiplication of vectors :", vec1 * vec2, "\n")
cat ("Division of vectors :", vec1 / vec2, "\n")
cat ("Modulo of vectors :", vec1 %% vec2, "\n")
cat ("Power operator :", vec1 ^ vec2)
Output:

BIHE Davangere Page 3


R programming lab

Addition of vectors : 2 5
Subtraction of vectors : -2 -1
Multiplication of vectors : 0 6
Division of vectors : 0 0.6666667
Modulo of vectors : 0 2
Power operator : 0 8

b. control structures
x <-5

if(x > 10){


print(paste(x, "is greater than 10"))
}else{
print(paste(x, "is less than 10"))
}

Output:
"5 is less than 10"
c.default values for arguments
divisible <- function(a, b = 3){
if(a %% b == 0)
{
return(paste(a, "is divisible by", b))
}
else
{
return(paste(a, "is not divisible by", b))
}
}
print(divisible(10, 5))
print(divisible(12))

Output:
[1] "10 is divisible by 5"
[1] "12 is divisible by 3"

BIHE Davangere Page 4


R programming lab

d. returning complex objects:


multi_return<- function() {
my_list<- list("color" = "red", "size" = 20, "shape" = "round")
return(my_list)
}
a <- multi_return()
print(a$color)
print(a$size)
print(a$shape)

Output:
[1] "red"
[1] 20
[1] "round"

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


a.Quick Sort
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)


print("before sorting")
print(arr)
result <- quickSort(arr)
print("after sorting")
print(result)

BIHE Davangere Page 5


R programming lab

Output:
"before sorting"
[1] 48 49 8 26 67 19 38 99 92 34
[1] "after sorting"
[1] 8 19 26 34 38 48 49 67 92 99

b. Binary search tree:


library(R6)

Node <- R6Class(


classname = 'Node',
public = list(

val = NULL,
left = NULL,
right = NULL,

initialize = function(val = NULL, left = NULL, right = NULL){

self$val <- val


self$left <- left
self$right <- right

}
)
)

BST <- R6Class(

classname = 'BST',

public = list(

root = NULL,
# node = NULL,
node=NULL,

insert = function(data){

if(is.null(self$root)){
self$node <- Node$new(data)
}else{
self$insert_recur(data, self$root)
}

},

insert_recur = function(data, cur_node){

BIHE Davangere Page 6


R programming lab

if(data < cur_node$val){


if(is.null(cur_node$self)){
cur_node$left <- Node$new(data)
}else{
insert_recur(data, cur_node$left)
}
}else if(data > cur_node$val){
if(is.null(cur_node$self)){
cur_node$right <- Node$new(data)
}else{
insert_recur(data, cur_node$right)
}
}else{
print('value already in tree')
}

},

get_height = function(cur_node){

if(is.null(cur_node$val)){
return(-1)
}else{
return(max(self$get_height(cur_node$left),self$get_height(cur_node$right))+1)
}
}

print(bst <- BST$new())


print(bst$insert(3))
print(bst$insert(2))
print(bst$insert(1))
print(bst$insert(5))
print(bst$insert(6))

print(bst$get_height(bst$root))
print(bst$get_height(bst$root$right))
print(bst$root)
print(bst$root$left)
print(bst$root$right)
print(bst$root$left$left)
print(bst$root$left$right)

BIHE Davangere Page 7


R programming lab

Output:
<BST>
Public:
clone: function (deep = FALSE)
get_height: function (cur_node)
insert: function (data)
insert_recur: function (data, cur_node)
node: NULL
root: NULL
<Node>
Public:
clone: function (deep = FALSE)
initialize: function (val = NULL, left = NULL, right = NULL)
left: NULL
right: NULL
val: 3
<Node>
Public:
clone: function (deep = FALSE)
initialize: function (val = NULL, left = NULL, right = NULL)
left: NULL
right: NULL
val: 2
<Node>
Public:
clone: function (deep = FALSE)
initialize: function (val = NULL, left = NULL, right = NULL)
left: NULL
right: NULL
val: 3
<Node>
Public:
clone: function (deep = FALSE)
initialize: function (val = NULL, left = NULL, right = NULL)
left: NULL
right: NULL
val: 5
<Node>
Public:
clone: function (deep = FALSE)
initialize: function (val = NULL, left = NULL, right = NULL)
left: NULL
right: NULL
val: 6
[1] -1
[1] -1
NULL
NULL
NULL

BIHE Davangere Page 8


R programming lab

5.Write a R program for calculating cumulative sums, and products minima maxima and
calculus.
x1 <- c(2, 4, 5, 7)
x2 <- c(2.4, 5.6, 3.4)

print(cumsum(x1))
print(cumsum(x2))

x1 <- c(2, 4, 5, 7)
x2 <- c(2.4, 5.6, 3.4)

print(cumprod(x1))
print(cumprod(x2))

x1 <- c(3, 6, 4, 2, 6, 7)
x2 <- c(-4, 6, 3)

print(cummin(x1))
print(cummin(x2))

x1 <- c(3, 6, 4, 2, 6, 7)
x2 <- c(-4, 6, 3)

print(cummax(x1))
print(cummax(x2))

Output:

BIHE Davangere Page 9


R programming lab

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


a. Gary’s mood
P=t(matrix(c(c(0.5,0.4,0.1),c(0.3,0.4,0.3),c(0.2,0.3,0.5)),nrow=3))
r<-apply(P,1,sum)
print(r)

Output:
[1] 1 1 1

7.Write a R program that include linear algebra operations on vectors and matrices
a =matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow =3,
ncol =3,
byrow =TRUE
)
cat("The 3x3matrix:\n")
print(a)

cat("Adding 1to every element:\n")


print(a +1)

cat("Subtracting 3fromeach element:\n")


print(a-3)

cat("Multiplying each element by 10:\n")


print(a *10)

cat("Squaring each element:\n")


print(a ^ 2)

cat("Doubled each element of original matrix:\n")


print(a *2)

Output:
The 3x3 matrix:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Adding 1 to every element:
[,1] [,2] [,3]
[1,] 2 3 4
[2,] 5 6 7
[3,] 8 9 10
Subtracting 3 from each element:
[,1] [,2] [,3]

BIHE Davangere Page 10


R programming lab

[1,] -2 -1 0
[2,] 1 2 3
[3,] 4 5 6
Multiplying each element by 10:
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 40 50 60
[3,] 70 80 90
Squaring each element:
[,1] [,2] [,3]
[1,] 1 4 9
[2,] 16 25 36
[3,] 49 64 81
Doubled each element of original matrix:
[,1] [,2] [,3]
[1,] 2 4 6
[2,] 8 10 12
[3,] 14 16 18

8.Write a R program for any visual representation of an object with creating graphs using
graphic functions: Plot(),Hist(),Linechart(),Pie(),Boxplot(),Scatterplots().

A. Plot:
barplot(airquality$Ozone,
main = 'Ozone Concenteration in air',
xlab = 'ozone levels', horiz = TRUE)

Output:

B.Histogram:
data(airquality)

hist(airquality$Temp, main ="La Guardia Airport's\


Maximum Temperature(Daily)",
xlab ="Temperature(Fahrenheit)",
xlim = c(50, 125), col ="yellow",
freq = TRUE)

BIHE Davangere Page 11


R programming lab

Output:

C.Linechart:
v <- c(17, 25, 38, 23, 41)
plot(v, type = "o")
Output:

D. piechart:
geeks<- c(23, 56, 20, 63)
labels <- c("Mumbai", "Pune", "Chennai", "Bangalore")

pie(geeks, labels)

Output:

BIHE Davangere Page 12


R programming lab

E.BoxPlot:
data(mtcars)
boxplot(disp ~ gear, data = mtcars,
main = "Displacement by Gear",
xlab = "Gear",
ylab = "Displacement")
Output:

F.scatterplot:
input <- mtcars[, c('wt', 'mpg')]

plot(x = input$wt, y = input$mpg,


xlab = "Weight",
ylab = "Milage",
xlim = c(1.5, 4),
ylim = c(10, 25),
main = "Weight vs Milage"
)

Output:

BIHE Davangere Page 13


R programming lab

9.Write a R program for with any dataset containing data frame objects, indexing and
sub setting data frames, and employ manipulating and analysing data.
stats <- data.frame(employe=c('A', 'B', 'C', 'D'),
salary=c(100, 200, 408, 23),
bonuspoint=c(17, 20, 3, 5))
print("stats Dataframe")
print(stats)
print(subset(x=stats, subset=bonuspoint>5, select=c(employe,bonuspoint)))

Output:
"stats Dataframe"

employe salary bonuspoint


1 A 100 17
2 B 200 20
3 C 408 3
4 D 23 5

employebonuspoint
1 A 17
2 B 20

BIHE Davangere Page 14


R programming lab

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


context for predictive purpose.
x <- c(153, 169, 140, 186, 128,
136, 178, 163, 152, 133)

y <- c(64, 81, 58, 91, 47, 57,


75, 72, 62, 49)

model <- lm(y~x)

print(model)

df<- data.frame(x = 182)


res <- predict(model, df)
cat("\nPredicted value of a person
with height = 182")
print(res)

png(file = "linearRegGFG.png")

plot(x, y, main = "Height vs Weight


Regression model")
abline(lm(y~x))

dev.off()

Output:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
-39.7137 0.6847

Predicted value of a person with height = 1821 84.9098

BIHE Davangere Page 15


R programming lab

BIHE Davangere Page 16


R programming lab

PART B:
1.write a R program to find the factorial of a number
fact<-function(num){
answer=1
for(i in 1:num){
answer=answer*i
}
print("factorial of a number is")
print(answer)

}
value <- readline(prompt="Enter value: ")
fact(value)

Output:
Enter value: 3
[1] "factorial of a number is"
[1] 6

2. write a program to convert Decimal to Binary using recursion in R


convert_to_binary <- function(decnum) {
if(decnum > 1) {
convert_to_binary(as.integer(decnum/2))
}
cat(decnum %% 2)
}
num = as.integer(readline(prompt="Enter a number: "))
print(convert_to_binary(num))
Output:
Enter a number: 5
101

3. write a R program to check Armstrong number

num = as.integer(readline(prompt="Enter a number: "))


sum = 0
temp = num
while(temp > 0) {
digit = temp %% 10
sum = sum + (digit ^ 3)
temp = floor(temp / 10)
}
if(num == sum) {
print(paste(num, "is an Armstrong number"))
} else {
print(paste(num, "is not an Armstrong number"))

BIHE Davangere Page 17


R programming lab

}
Output:
Enter a number: 10
[1] "10 is not an Armstrong number"

4.write a R program to Add Two Vectors


fv <- 1:4
cat("The first vector is: ", fv, "\n")
sv <- 5:8
cat("The second vector is: ", sv, "\n")

add <- fv + sv
cat("The final vector is: ", add)

Output:
The first vector is: 1 2 3 4
The second vector is: 5 6 7 8
The final vector is: 6 8 10 12

5.Write a Fibonacci Sequence Using Recursion in R


recurse_fibonacci <- function(n) {
if (n <= 1){
return(n)
} else {

return(recurse_fibonacci(n-1) + recurse_fibonacci(n-2))
}
}

nterms = as.integer(readline(prompt="How many terms? "))

if(nterms <= 0) {
print("please enter a positive integer")
} else {
print("Fibonacci Sequence: ")
for(i in 0:(nterms - 1)){
print(recurse_fibonacci(i))
}
}
Output:
How many terms? 5
[1] "Fibonacci Sequence: "
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3

BIHE Davangere Page 18


R programming lab

6.Write a R Program to Find H.C.F or G.C.D


hcf <- function(x, y) {
while(y) {
temp = y
y = x %% y
x = temp
}
return(x)
}
num1 = as.integer(readline(prompt = "Enter first number: "))
num2 = as.integer(readline(prompt = "Enter second number: "))
print(paste("The H.C.F. of", num1,"and", num2,"is", hcf(num1, num2)))

Output:
Enter first number: 72
Enter second number: 124
[1] "The H.C.F. of 72 and 124 is 4"

7.Write a R Program to Check for Leap Year

year = as.integer(readline(prompt="Enter a year: "))


if((year %% 4) == 0) {
if((year %% 100) == 0) {
if((year %% 400) == 0) {
print(paste(year,"is a leap year"))
} else {
print(paste(year,"is not a leap year"))
}
} else {
print(paste(year,"is a leap year"))
}
} else {
print(paste(year,"is not a leap year"))
}
Output:
Enter a year: 2000
[1] "2000 is a leap year"
Enter a year: 2023
[1] "2023 is not a leap year"

BIHE Davangere Page 19


R programming lab

8.Write a R Program to Find 3rd Minimum and 3rd Maximum of Numbers.


arr <- c(9, 8, 7, 6, 5, 4, 3, 2, 1,10,11)
arr1<-sort(arr)
print("sorted array is")
print(arr1)
l<-length(arr1)
print("3rd mininum element")
print(arr1[3])
print("3rd maximum element")
print(arr1[l-2])

Output:
[1] "sorted array is"
[1] 1 2 3 4 5 6 7 8 9 10 11
[1] "3rd mininum element"
[1] 3
[1] "3rd maximum element"
[1] 9

9.Write a R Program for Multiplication Table


num = as.integer(readline(prompt = "Enter a number: "))
for(i in 1:10) {
print(paste(num,'x', i, '=', num*i))
}
Output:
Enter a number: 10
[1] "10 x 1 = 10"
[1] "10 x 2 = 20"
[1] "10 x 3 = 30"
[1] "10 x 4 = 40"
[1] "10 x 5 = 50"
[1] "10 x 6 = 60"
[1] "10 x 7 = 70"
[1] "10 x 8 = 80"
[1] "10 x 9 = 90"
[1] "10 x 10 = 100"

BIHE Davangere Page 20


R programming lab

10.Write a R program to Check Prime Number


num = as.integer(readline(prompt="Enter a number: "))
flag = 0
if(num > 1) {
for(i in 2:(num-1)) {
if ((num %% i) == 0) {
flag = 1
break
}
}
}

if(flag == 0) {
print(paste(num,"is a prime number"))
} else {
print(paste(num,"is not a prime number"))
}
Output:
Enter a number: 3
[1] "3 is a prime number"
Enter a number: 9
[1] "9 is not a prime number"

BIHE Davangere Page 21

You might also like