You are on page 1of 36

R N S Institute of Technology

RR Nagar Post, Bengaluru – 560 098.

Academic Year: June 2023 – September 2023

Programme B E – CSE (Data Science)


Semester IV
Course Code 21CSL483
Course Title R PROGRAMMING LABORATORY
Mr. Saravana M K
Course Plan Assistant Professor,
Author Department of CSE (Data Science)
RNS Institute of Technology, Bengaluru.
21CSL483: R PROGRAMMING Laboratory

21CSL483: R Programming Laboratory

Course objectives
Upon completion of this course, students are expected to:
1. Explore and understand how R and R Studio Interactive environment
2. To learn and practice programming techniques using R programming
3. Read Structured Data into R from various sources
4. Understand the different data structures, data types in R
5. To develop small applications using R Programming

Course Outcomes
After studying this course, students will be able to:

21CSL483.1 Understand the fundamental syntax of R through readings and Practical


Sessions
21CSL483.2 Experiment with the concepts such as data types, iteration, control
structures, functions and Boolean operators by writing R programs
21CSL483.3 Examine a variety of data formats into R using R- Studio
21CSL483.4 Create a data to use for small applications using R Programming

CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
21CSL483.1 3
21CSL483.2 3
21CSL483.3 3
21CSL483.4 3

©Department of CSE (DS), RNSIT, Bengaluru. 2 / 36


21CSL483: R PROGRAMMING Laboratory

Date EXPERIMENT NAME Page


Week No
05/06– 09/06 Installation and Configuration of R and R Studio 04
Week - 1
12/06– 16/06 Module 1- Programs 05
Week - 2
19/06– 23/06 Module 1- Programs 09
Week - 3
26/06 - 30/06 Module 2- Programs 15
Week - 4
03/07 -07/07 Module 2- Programs 16
Week 5
10/07 -14/07 Lab Internal Assessment
Week 6
17/07 – 21/07 Module 3- Programs 20
Week 7
24/07 – 28/07 Module 3- Programs 21
Week 8
31/07 – 4/08 Module 4- Programs 26
Week 9
7/08 – 11/08 Module 4- Programs 27
Week 10
14/08 – 18/08 Module 5- Programs 30
Week 11
21/08 – 25/08 Module 5- Programs
Week 12
28/08 – 01/09 Lab Internal Assessment
Week 13

©Department of CSE (DS), RNSIT, Bengaluru. 3 / 36


21CSL483: R PROGRAMMING Laboratory

Date Laboratory Conduction Plan


05/06– 09/06 1. Demo of Installation and Configuration of R Studio
Week - 1 https://www.youtube.com/watch?v=YrEe2TLr3MI

©Department of CSE (DS), RNSIT, Bengaluru. 4 / 36


21CSL483: R PROGRAMMING Laboratory

Module 1:
1. Write a program to create a sequence of numbers from 20 to 50 and find the mean
of numbers from 20 to 60 and sum of numbers from 51 to 91.

print ("Sequence of numbers from 20 to 50:")


print (seq (20,50))
print ("Mean of numbers from 20 to 60:")
print (mean (20:60))
print ("Sum of numbers from 51 to 91:")
print (sum (51:91))

Output:
[1] "Sequence of numbers from 20 to 50:"
> print (seq (20,50))
[1] 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
[23] 42 43 44 45 46 47 48 49 50
> print ("Mean of numbers from 20 to 60:")
[1] "Mean of numbers from 20 to 60:"
> print (mean (20:60))
[1] 40
> print ("Sum of numbers from 51 to 91:")
[1] "Sum of numbers from 51 to 91:"
> print (sum (51:91))
[1] 2911

2. Write a program to create a vector which contains 10 random integer values


between -50 and +50.

v = sample (-50:50, 10, replace=TRUE)


print ("Content of the vector :")
print ("10 random integer values between -50 and +50 :")
print (v)

Output:
print ("Content of the vector:")
[1] "Content of the vector:"
> print ("10 random integer values between -50 and +50 :")
[1] "10 random integer values between -50 and +50:"
> print (v)
[1] 8 -33 -14 -22 -18 19 43 -4 17 31

©Department of CSE (DS), RNSIT, Bengaluru. 5 / 36


21CSL483: R PROGRAMMING Laboratory

3. Write a program to extract first 10 English letter in lower case and last 10 letters in
upper case and extract letters between 22nd to 24th letters in upper case

print("First 10 letters in lower case:") t = head(letters, 10)


print(t)
print("Last 10 letters in upper case:") t = tail(LETTERS, 10)
print(t)
print("Letters between 22nd to 24th letters in upper case:")
e = tail(LETTERS[22:24])
print(e)

Output:
> print("First 10 letters in lower case:")
[1] "First 10 letters in lower case:"
> t = head(letters, 10)
> print(t)
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
> print("Last 10 letters in upper case:")
[1] "Last 10 letters in upper case:"
> t = tail(LETTERS, 10)
> print(t)
[1] "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"
> print("Letters between 22nd to 24th letters in upper case:")
[1] "Letters between 22nd to 24th letters in upper case:"
> e = tail(LETTERS[22:24])
> print(e)
[1] "V" "W" "X"

4. Write a program to find the maximum and the minimum value of a given vector

nums = c(10, 20, 30, 40, 50, 60)


print('Original vector:') print(nums)
print(paste("Maximum value of the said vector:",max(nums)))
print(paste("Minimum value of the said vector:",min(nums)))

Output:
[1] "Original vector:"
> print(nums)
[1] 10 20 30 40 50 60
> print(paste("Maximum value of the said vector:",max(nums)))
[1] "Maximum value of the said vector: 60"
> print(paste("Minimum value of the said vector:",min(nums)))
[1] "Minimum value of the said vector: 10"

©Department of CSE (DS), RNSIT, Bengaluru. 6 / 36


21CSL483: R PROGRAMMING Laboratory

5. Write a program to create three vectors numeric data, character data and logical
data. Display the content of the vectors and their type
a = c(1, 2, 5, 3, 4, 0, -1, -3)
b = c("Red", "Green", "White")
c = c(TRUE, TRUE, TRUE, FALSE, TRUE, FALSE)
print(a)
print(typeof(a))
print(b)
print(typeof(b))
print(c)
print(typeof(c))

Output:
[1] 1 2 5 3 4 0 -1 -3
> print(typeof(a))
[1] "double"
> print(b)
[1] "Red" "Green" "White"
> print(typeof(b))
[1] "character"
> print(c)
[1] TRUE TRUE TRUE FALSE TRUE FALSE
> print(typeof(c))
[1] "logical"

6. Write a R program to draw an empty plot and an empty plot specify the axes
limits of the graphic.
#print("Empty plot:")
plot.new()
#print("Empty plot specify the axes limits of the graphic:")
plot(1, type="n", xlab="t in sec", ylab="Sensor output", xlim=c(0,
20), ylim=c(0, 20))

Output:

©Department of CSE (DS), RNSIT, Bengaluru. 7 / 36


21CSL483: R PROGRAMMING Laboratory

7. Write a R program to create a simple bar plot of five subjects marks.


marks = c(70, 95, 80, 74)
barplot (marks,
main = "Comparing marks of 5 subjects",
xlab = "Marks",
ylab = "Subject",
names.arg = c("English", "Science", "Math.", "Hist."),
col = "darkred",
horiz = FALSE)

Output:

8. Write a R program to create bell curve of a random normal distribution.


n = floor(rnorm(10000, 500, 100))
t = table(n)
barplot(t)

Output:

©Department of CSE (DS), RNSIT, Bengaluru. 8 / 36


21CSL483: R PROGRAMMING Laboratory

9. Write a R program to compute sum, mean and product of a given vector elements.
nums = c(10, 20, 30)
print('Original vector:')
print(nums)
print(paste("Sum of vector elements:",sum(nums)))
print(paste("Mean of vector elements:",mean(nums)))
print(paste("Product of vector elements:",prod(nums)))

Output:
[1] "Original vector:"
> print(nums)
[1] 10 20 30
> print(paste("Sum of vector elements:",sum(nums)))
[1] "Sum of vector elements: 60"
> print(paste("Mean of vector elements:",mean(nums)))
[1] "Mean of vector elements: 20"
> print(paste("Product of vector elements:",prod(nums)))
[1] "Product of vector elements: 6000"

10. Write a R program to create the system's idea of the current date with and without
time.
print("System's idea of the current date with and without
time:")
print(Sys.Date())
print(Sys.time())

Output:
[1] "System's idea of the current date with and without time:"
> print(Sys.Date())
[1] "2023-05-12"
> print(Sys.time())
[1] "2023-05-12 09:49:35 IST"

11. Write a program to create three vectors a,b,c with 3 integers. Combine the three
vectors to become a 3×3 matrix where each column represents a vector. Print the
content of the matrix
a<-c(1,2,3)
b<-c(4,5,6)
c<-c(7,8,9)
m<-cbind(a,b,c)
print("Content of the said matrix:")
print(m)
©Department of CSE (DS), RNSIT, Bengaluru. 9 / 36
21CSL483: R PROGRAMMING Laboratory

Output:
[1] "Content of the said matrix:"
> print(m)
a b c
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

12. Write a R program to create a 5 × 4 matrix , 3 × 3 matrix with labels and fill the
matrix by rows and 2 × 2 matrix with labels and fill the matrix by columns

m1 = matrix(1:20, nrow=5, ncol=4) print("5 × 4 matrix:")


print(m1)
cells = c(1,3,5,7,8,9,11,12,14)
rnames = c("Row1", "Row2", "Row3")
cnames = c("Col1", "Col2", "Col3")
m2 = matrix(cells, nrow=3, ncol=3, byrow=TRUE,
dimnames=list(rnames, cnames)) print("3 × 3 matrix with
labels, filled by rows: ")
print(m2)
print("3 × 3 matrix with labels, filled by columns: ")
m3 = matrix(cells, nrow=3, ncol=3, byrow=FALSE,
dimnames=list(rnames, cnames))
print(m3)

Output:
[1] "5 × 4 matrix:"
> print(m1)
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
> print("3 × 3 matrix with labels, filled by rows: ")
[1] "3 × 3 matrix with labels, filled by rows: "
> print(m2)
Col1 Col2 Col3
Row1 1 3 5
Row2 7 8 9
Row3 11 12 14
> print("3 × 3 matrix with labels, filled by columns: ")
[1] "3 × 3 matrix with labels, filled by columns: "
> print(m3)
Col1 Col2 Col3
Row1 1 7 11
Row2 3 8 12
Row3 5 9 14

©Department of CSE (DS), RNSIT, Bengaluru. 10 / 36


21CSL483: R PROGRAMMING Laboratory

13. Write a R program to find common elements from multiple vectors.

x = c (10, 20, 30, 20, 20, 25, 29, 26)


y = c (10, 50, 30, 20, 20, 35, 19, 56)
z = c (10, 40, 30, 20, 20, 25, 49, 26)
print ("Original Vectors:")
print ("x: ") print(x)
print("y: ") print(y)
print("z: ") print(z)
print ("Common elements from above vectors:")
result = intersect(intersect(x,y),z)
print (result)

Output:
[1] "Original Vectors:"
> print("x: ")
[1] "x: "
> print(x)
[1] 10 20 30 20 20 25 29 26
> print("y: ")
[1] "y: "
> print(y)
[1] 10 50 30 20 20 35 19 56
> print("z: ")
[1] "z: "
> print(z)
[1] 10 40 30 20 20 25 49 26
> print("Common elements from above vectors:")
[1] "Common elements from above vectors:"
> result = intersect(intersect(x,y),z)
> print(result)
[1] 10 20 30

14. Write a R program to extract every nth element of a given vector.

v <- 1:100
print("Original vector:") print(v)
print("After extracting every 5th element of the said vector:")
n <- v[seq(1, length(v), 5)]
print(n)

©Department of CSE (DS), RNSIT, Bengaluru. 11 / 36


21CSL483: R PROGRAMMING Laboratory

Output:
[1] "Original vector:"
> print(v)
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
[17] 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
[33] 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
[49] 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
[65] 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
[81] 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
[97] 97 98 99 100
> print("After extracting every 5th element of the said vector:")
[1] "After extracting every 5th element of the said vector:"
> n <- v[seq(1, length(v), 5)]
> print(n)
[1] 1 6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96

15. Write a program to list the distinct values in a vector from a given vector.

v = c(10, 10, 10, 20, 30, 40, 40, 40, 50)


print("Original vector:")
print(v)
print("Distinct values of the said vector:")
print(unique(v))

Output:
[1] "Original vector:"
> print(v)
[1] 10 10 10 20 30 40 40 40 50
> print("Distinct values of the said vector:")
[1] "Distinct values of the said vector:"
> print(unique(v))
[1] 10 20 30 40 50

16. Write a program to find the elements of a given vector that are not in another
given vector.

a = c(0, 10, 10, 10, 20, 30, 40, 40, 40, 50, 60)
b = c(10, 10, 20, 30, 40, 40, 50)
print("Original vector-1:")
print(a)
print("Original vector-2:")
print(b)
print("Elements of a that are not in b:")
result = setdiff(a, b)

©Department of CSE (DS), RNSIT, Bengaluru. 12 / 36


21CSL483: R PROGRAMMING Laboratory

print(result)

Output:
[1] "Original vector-1:"
> print(a)
[1] 0 10 10 10 20 30 40 40 40 50 60
> print("Original vector-2:")
[1] "Original vector-2:"
> print(b)
[1] 10 10 20 30 40 40 50
> print("Elements of a that are not in b:")
[1] "Elements of a that are not in b:"
> result = setdiff(a, b)
> print(result)
[1] 0 60

17. Write a R program to access the last value in a given vector.

x = c(10, 20, 30, 20, 20, 25, 9, 26)


print("Original Vectors:")
print(x)
print("Access the last value of the said vector:")
print(tail(x, n=1))

Output:
[1] "Original Vectors:"
> print(x)
[1] 10 20 30 20 20 25 9 26
> print("Access the last value of the said vector:")
[1] "Access the last value of the said vector:"
> print(tail(x, n=1))
[1] 26

18. Write a R program to find nth highest value in a given vector

x = c(10, 20, 30, 20, 20, 25, 9, 26)


print("Original Vectors:")
print(x)
print("nth highest value in a given vector:")
print("n = 1")
n = 1
print(sort(x, TRUE)[n])
print("n = 2")
n = 2

©Department of CSE (DS), RNSIT, Bengaluru. 13 / 36


21CSL483: R PROGRAMMING Laboratory

print(sort(x, TRUE)[n])
print("n = 3")
n = 3
print(sort(x, TRUE)[n])
print("n = 4")
n = 4
print(sort(x, TRUE)[n])

Output:
[1] "Original Vectors:"
> print(x)
[1] 10 20 30 20 20 25 9 26
> print("nth highest value in a given vector:")
[1] "nth highest value in a given vector:"
> print("n = 1")
[1] "n = 1"
> n = 1
> print(sort(x, TRUE)[n])
[1] 30
> print("n = 2")
[1] "n = 2"
> n = 2
> print(sort(x, TRUE)[n])
[1] 26
> print("n = 3")
[1] "n = 3"
> n = 3
> print(sort(x, TRUE)[n])
[1] 25
> print("n = 4")
[1] "n = 4"
> n = 4
> print(sort(x, TRUE)[n])
[1] 20

19. Write a R program to create a vector of a specified type and length. Create vector
of numeric, complex, logical and character types of length 6.

x = vector("numeric", 5)
print("Numeric Type:")
print(x)
c = vector("complex", 5)
print("Complex Type:")
print(c)

©Department of CSE (DS), RNSIT, Bengaluru. 14 / 36


21CSL483: R PROGRAMMING Laboratory

l = vector("logical", 5)
print("Logical Type:")
print(l)
chr = vector("character", 5)
print("Character Type:")
print(chr)

Output:
> x = vector("numeric", 5)
> print("Numeric Type:")
[1] "Numeric Type:"
> print(x)
[1] 0 0 0 0 0
> c = vector("complex", 5)
> print("Complex Type:")
[1] "Complex Type:"
> print(c)
[1] 0+0i 0+0i 0+0i 0+0i 0+0i
> l = vector("logical", 5)
> print("Logical Type:")
[1] "Logical Type:"
> print(l)
[1] FALSE FALSE FALSE FALSE FALSE
> chr = vector("character", 5)
> print("Character Type:")
[1] "Character Type:"
> print(chr)
[1] "" "" "" "" ""

©Department of CSE (DS), RNSIT, Bengaluru. 15 / 36


21CSL483: R PROGRAMMING Laboratory

Module 2

1. Write a program to get all prime numbers up to a given number (based on the
sieve of Eratosthenes)

prime_numbers <- function(n) {


if (n >= 2) {
x = seq(2, n)
prime_nums = c()
for (i in seq(2, n)) {
if (any(x == i)) {
prime_nums = c(prime_nums, i)
x = c(x[(x %% i) != 0], i)
}
}
return(prime_nums)
}
else
{
stop("Input number should be at least 2.")
}
}
prime_numbers(12)
Output:
2
3
5
7
11

2. Write a program to find the factors of a given number

print_factors = function(n) {
print(paste("The factors of",n,"are:"))
for(i in 1:n) {
if((n %% i) == 0) {
print(i)
} } }
print_factors(4)
print_factors(7)
print_factors(12)

©Department of CSE (DS), RNSIT, Bengaluru. 16 / 36


21CSL483: R PROGRAMMING Laboratory

Output:
> print_factors(4)
[1] "The factors of 4 are:"
[1] 1
[1] 2
[1] 4
> print_factors(7)
[1] "The factors of 7 are:"
[1] 1
[1] 7
> print_factors(12)
[1] "The factors of 12 are:"
[1] 1
[1] 2
[1] 3
[1] 4
[1] 6
[1] 12

3. Write a script that will print "Even Number" if the variable x is an even number,
otherwise print "Not Even":

x <- 3 # Change x to test


if (x%%2 == 0){
print('Even Number')
}else{
print('Not Even')
}

Output:
> x <- 3 # Change x to test
> if (x%%2 == 0){
+ print('Even Number')
+ }else{
+ print('Not Even')
+ }
[1] "Not Even"

4. Write a script that will print 'Is a Matrix' if the variable x is a matrix, otherwise
print "Not a Matrix". Hint: You may want to check out help (is.matrix)

x <- matrix()
if (is.matrix(x)){
print('Is a Matrix')
}else{
print("Not a Matrix")

©Department of CSE (DS), RNSIT, Bengaluru. 17 / 36


21CSL483: R PROGRAMMING Laboratory

Output:
> x <- matrix()
> if (is.matrix(x)){ print('Is a Matrix')
+ }else{
+ print("Not a Matrix")
+ }
[1] "Is a Matrix"

5. R program to find inverse of a Matrix

# Create 3 different vectors # using combine method.


a1 <- c(3, 2, 5)
a2 <- c(2, 3, 2)
a3 <- c(5, 2, 4)
# bind the three vectors into a matrix using rbind() which is
row-wise binding
A <- rbind (a1, a2, a3)
# print the original matrix
print(A)
# Use the solve() function to calculate the inverse.
T1 <- solve(A)
# print the inverse of the matrix.
print(T1)

Output:
> A <- rbind (a1, a2, a3)
> # print the original matrix
> print(A)
[,1] [,2] [,3]
a1 3 2 5
a2 2 3 2
a3 5 2 4
> # Use the solve() function to calculate the inverse.
> T1 <- solve(A)
> # print the inverse of the matrix.
> print(T1)
a1 a2 a3
[1,] -0.29629630 -0.07407407 0.4074074
[2,] -0.07407407 0.48148148 -0.1481481
[3,] 0.40740741 -0.14814815 -0.1851852

6. R Program to find determinant of a matrix

# Create 3 different vectors.


a1 <- c(3, 2, 8)

©Department of CSE (DS), RNSIT, Bengaluru. 18 / 36


21CSL483: R PROGRAMMING Laboratory

a2 <- c(6, 3, 2)
a3 <- c(5, 2, 4)

# Bind the 3 matrices row-wise


# using the rbind() function.
A <- rbind(a1, a2, a3)
# determinant of matrix
print(det(A))

Output:
> # determinant of matrix
> print(det(A))
[1] -28

7. R Program to draw the sine wave

t=seq(0,10,0.1)
y=sin(t)
plot(t,y,type="l", xlab="time", ylab="Sine wave")

Output:

library(ggplot2)
qplot(t,y,geom="path", xlab="time", ylab="Sine wave")

Output:

©Department of CSE (DS), RNSIT, Bengaluru. 19 / 36


21CSL483: R PROGRAMMING Laboratory

Module 3

1. Write a R program to create a Dataframe

df <- data.frame(
Training = c("Strength", "Stamina", "other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)

# print the dataframe


print(df)

Output:
> print(df)
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 other 120 45

2. Write a R program to create a summary of the above Dataframe


summary(df)
> summary(df)
Training Pulse Duration
Length:3 Min. :100.0 Min. :30.0
Class :character 1st Qu.:110.0 1st Qu.:37.5
Mode :character Median :120.0 Median :45.0
Mean :123.3 Mean :45.0
3rd Qu.:135.0 3rd Qu.:52.5
Max. :150.0 Max. :60.0

3. Write a R program to use single brackets [ ], double brackets [[ ]] or $ to


access columns from a data frame:

df <- data.frame(
Training = c("Strength", "Stamina", "other"),
©Department of CSE (DS), RNSIT, Bengaluru. 20 / 36
21CSL483: R PROGRAMMING Laboratory

Pulse = c(100, 150, 120),


Duration = c(60, 30, 45)
)
# print the dataframe
print(df)

df[1]
df[["Training"]]
df$Training
Output:
> df[1]
Training
1 Strength
2 Stamina
3 other
> df[["Training"]]
[1] "Strength" "Stamina" "other"
> df$Training
[1] "Strength" "Stamina" "other"

4. Write a R program to use rbind() function to add new rows in a Data Frame:
df <- data.frame(
Training = c("Strength", "Stamina", "other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
# Add a new row
New_row_DF <- rbind(df, c("strength",110,110))
# Print the new row
New_row_DF
Output:

> # Print the new row


> New_row_DF
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 other 120 45
4 strength 110 110

©Department of CSE (DS), RNSIT, Bengaluru. 21 / 36


21CSL483: R PROGRAMMING Laboratory

5. Write a R program to use cbind() function to add new rows in a Data Frame:
df <- data.frame(
Training = c("Strength", "Stamina", "other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)

# Add a new column


New_col_DF <- cbind(df, steps= c(6000,11000,9000))
# Print the new row
New_col_DF
Output:
# Print the new row
> New_col_DF
Training Pulse Duration steps
1 Strength 100 60 6000
2 Stamina 150 30 11000
3 other 120 45 9000

6. Write a R program to read a CSV file as input to store as a Data Frame:


# read in data from a CSV file
dataframe <- read.csv("C:/Priya/Module 3/iris.csv")

# print the dataframe


print(dataframe)
Output:
print(dataframe)
sepal.length sepal.width petal.length petal.width variety
1 5.1 3.5 1.4 0.2 Setosa
2 4.9 3.0 1.4 0.2 Setosa
3 4.7 3.2 1.3 0.2 Setosa
4 4.6 3.1 1.5 0.2 Setosa
.
.
51 7.0 3.2 4.7 1.4 Versicolor
52 6.4 3.2 4.5 1.5 Versicolor
53 6.9 3.1 4.9 1.5 Versicolor
54 5.5 2.3 4.0 1.3 Versicolor
.
.
147 6.3 2.5 5.0 1.9 Virginica
148 6.5 3.0 5.2 2.0 Virginica
149 6.2 3.4 5.4 2.3 Virginica
150 5.9 3.0 5.1 1.8 Virginica

7. Write a R program to find maximum petal length from the Data Frame:
©Department of CSE (DS), RNSIT, Bengaluru. 22 / 36
21CSL483: R PROGRAMMING Laboratory

pe.len <- max(dataframe$petal.length)


print(pe.len)
Output:
print(pe.len)
[1] 6.9

8. Write a R program to read a Text file as input to store as a Data Frame:


# read in the text file
data <- read.delim("C:/Priya/Module 3/text.txt")

# print the dataframe


print(data)
Output:
> # print the dataframe
> print(data)
Hi
1 Hello
2 How are you

9. Write a R program to use apply function to Rows or Columns of matrix


In R, apply () function is used to apply a function to a matrix or an array, or to a specific margin (row
or column) of a matrix or array. Here is the general syntax of apply () function:
apply (X, MARGIN, FUN, ...)

Where,
X: the matrix or array to apply the function to
MARGIN: an integer specifying which margin to apply the function to. Use 1 to apply the function
to each row, 2 to apply the function to each column, or c(1,2) to apply the function to both rows and
columns
FUN: the function to apply
...: additional arguments to the function FUN
X <- matrix(c( 1, 2, 3, 4, 5, 6), nrow=2, ncol=3)
apply (X, 1, sum)

Output:
> apply(X, 1, sum)
[1] 9 12

©Department of CSE (DS), RNSIT, Bengaluru. 23 / 36


21CSL483: R PROGRAMMING Laboratory

apply(X, 2, sum)

Output:
> apply(X, 2, sum)
[1] 3 7 11

10. Write a R program to use custom function to Rows or Columns of matrix

X <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)


myfun <- function(x) {
return(2 * x)
}
apply(X, 1, myfun)

Output:
> apply(X, 1, myfun)
[,1] [,2]
[1,] 2 4
[2,] 6 8
[3,] 10 12

apply(X, 2, myfun)

Output:
> apply(X, 2, myfun)
[,1] [,2] [,3]
[1,] 2 6 10
[2,] 4 8 12

11. Write a R program to create a List containing Strings, Numbers, Vectors and
logical values
# create a list
my_list <- list("Hello", 123, c(1, 2, 3), TRUE)
# print the list
print(my_list)
Output:
> print(my_list)
[[1]]
[1] "Hello"

[[2]]
[1] 123

[[3]]
[1] 1 2 3

©Department of CSE (DS), RNSIT, Bengaluru. 24 / 36


21CSL483: R PROGRAMMING Laboratory

[[4]]
[1] TRUE

# Access the first element of the list.

print(my_list[1])

Output:
> print(my_list[1])
[[1]]
[1] "Hello"

# Access the list element using the name of the element.


print(my_list$A_Matrix)
Output:
> print(my_list$A_Matrix)
NULL

# create a list with named elements


my_list2 <- list (name = "Alice", age = 30)
print (my_list2 )
Output:
> print (my_list2 )
$name
[1] "Alice"

$age
[1] 30

# Access the list element using the name of the element.


print(my_list2$name)
Output:
> print(my_list2$name)
[1] "Alice"

©Department of CSE (DS), RNSIT, Bengaluru. 25 / 36


21CSL483: R PROGRAMMING Laboratory

©Department of CSE (DS), RNSIT, Bengaluru. 26 / 36


21CSL483: R PROGRAMMING Laboratory

Module 4

1. Write a R program to find a factorial using function().


# Using the function() keyword to create a factorial function
factorial <- function(n) {
if (n == 0 || n == 1) {
return(1)
} else {
result <- 1
for (i in 1:n) {
result <- result * i
}
return(result)
}
}

# Example usage
number <- 5
factorial_result <- factorial(number)
print(paste("The factorial of", number, "is", factorial_result))

Output:
> number <- 5
> factorial_result <- factorial(number)
> print(paste("The factorial of", number, "is", factorial_result))
[1] "The factorial of 5 is 120"

2. Write a R code to find the sequence of number from 32 to 44, to find the mean
of numbers from 25 to 82 and to find a sum of number from 41 to 68
# To create the sequence of number from 32 to 44
print(seq(32,44))
# To create the mean of numbers from 25 to 82
print(mean(25:82)
# To create a sum of number from 41 to 68
print(sum(41:68)
Output:
> # To create the sequence of number from 32 to 44
> print(seq(32,44))
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
> # To create the mean of numbers from 25 to 82
> print(mean(25:82))
[1] 53.5
> # To create a sum of number from 41 to 68
> print(sum(41:68))
[1] 1526
©Department of CSE (DS), RNSIT, Bengaluru. 27 / 36
21CSL483: R PROGRAMMING Laboratory

3. Write a R program to create functions with arguments.


# Create a function with arguments
new.function <- function( a=3, b=6) {
result <- a* b
print(result)
}
# Call the function without giving any arguments
new.funtion()
#Call the function with giving new values of the arguments
new.function(9,5)
Output:
[1] 18
[1] 45

4. Write a R program to create a plot using functions.


plot( 1,3)
Output:

plot(c(1,3,5,7,9,11),c(2,7,5,10,8,10),type='o',lt=3,col='pink',lwd=4, main= "This is


graph",col.main='blue', xlab="Time", ylab="Performance")
Output:

©Department of CSE (DS), RNSIT, Bengaluru. 28 / 36


21CSL483: R PROGRAMMING Laboratory

5. Write a R program to create a different plots using functions.


# Plot out the graphs using various options
plot(x,cos(x),col=c('blue','orange'), type='o', pch=19,lwd =2, cex = 1.5)
plot(x,x*2,col='red', type='l')
plot(x,x^2/3+4.2,col='violet',type='o',lwd=2,lty =1)
plot(c(1,3,5,7,9,11),c(2,7,5,10,8,10), type='o',lty = 3,col='pink',lwd=4)
plot(x <- seq(1,10,0.5),50 * x/(x+2), col = c('green','darkgreen'),type='h')
plot(x,log(x),col='orange',type='s')
Output:

©Department of CSE (DS), RNSIT, Bengaluru. 29 / 36


21CSL483: R PROGRAMMING Laboratory

6. Write a R program to install and load the scatterplot3d package

# Install and load the scatterplot3d package


install.packages("scatterplot3d")
library(scatterplot3d)

# Sample data
x <- c(1, 3, 5, 7, 9, 11)
y <- c(2, 7, 5, 10, 8, 10)
z <- c(3, 5, 7, 2, 6, 9)

# Create a 3D scatter plot


scatter3D(x, y, z,
clab = c("sepal", "width (cm)"),
main = "3D Scatter Plot",
xlab = "X-axis",
ylab = "Y-axis",
©Department of CSE (DS), RNSIT, Bengaluru. 30 / 36
21CSL483: R PROGRAMMING Laboratory

zlab = "Z-axis",
pch = 16,
col = "blue"
)
Output:

Module 5
1.
a) Write R program to create an S3 class studentRecord for objects that are a list
with the named elements ‘name’, ‘subjects completed’, ‘grades’, and ‘credit’.
b) Write a studentRecord method for the generic function mean, which returns a
weighted GPA, with subjects weighted by credit.
c) Write a studentRecord method for print, which employs some nice formatting,
perhaps arranging subjects by year code.
d) Finally create a further class for a cohort of students, and write methods for
mean and print which, when applied to a cohort, apply mean or print to each
student in the cohort.
# Define the studentRecord class
studentRecord <- function(name, subjects_completed, grades, credit) {
record <- list(
name = name,
subjects_completed = subjects_completed,
grades = grades,
©Department of CSE (DS), RNSIT, Bengaluru. 31 / 36
21CSL483: R PROGRAMMING Laboratory

credit = credit
)
class(record) <- "studentRecord"
return(record)
}

# Define the mean method for studentRecord


mean.studentRecord <- function(object) {
weighted_gpa <- sum(object$grades * object$credit) / sum(object$credit)
return(weighted_gpa)
}

# Define the print method for studentRecord


print.studentRecord <- function(object) {
cat("Name: ", object$name, "\n")
cat("Subjects Completed: ", paste(object$subjects_completed, collapse = ", "), "\n")
cat("Grades: ", paste(object$grades, collapse = ", "), "\n")
cat("Credit: ", paste(object$credit, collapse = ", "), "\n")
}

# Define the cohort class


cohort <- function(students) {
cohort <- list(students = students)
class(cohort) <- "cohort"
return(cohort)
}

# Define the mean method for cohort


mean.cohort <- function(object) {
sapply(object$students, mean)
}

©Department of CSE (DS), RNSIT, Bengaluru. 32 / 36


21CSL483: R PROGRAMMING Laboratory

# Define the print method for cohort


print.cohort <- function(object) {
for (student in object$students) {
print(student)
cat("\n")
}
}
# Create student records
student1 <- studentRecord(
name = "Alice",
subjects_completed = c("Math", "English", "Science"),
grades = c(80, 90, 85),
credit = c(3, 4, 3)
)

student2 <- studentRecord(


name = "Bob",
subjects_completed = c("History", "Physics"),
grades = c(75, 88),
credit = c(4, 3)
)

# Calculate mean GPA for a student record


mean_student1 <- mean(student1)
print(mean_student1)

# Print a student record


print(student1)

# Create a cohort of students


cohort1 <- cohort(list(student1, student2))

©Department of CSE (DS), RNSIT, Bengaluru. 33 / 36


21CSL483: R PROGRAMMING Laboratory

# Calculate mean GPA for a cohort


mean_cohort1 <- mean(cohort1)
print(mean_cohort1)

# Print a cohort of students


print(cohort1)

Let Omega be an ordered vector of numbers and define a subset of Omega to be an


ordered subvector. Define a class set for subsets of Omega and write functions that
perform union, intersection, and complementation on objects of class set. Do not use
R’s built-in functions union, intersect, setdiff, or setequal.
# Define the set class
set <- function(elements) {
obj <- list(elements = sort(unique(elements)))
class(obj) <- "set"
return(obj)
}

# Define the union function for sets


union.set <- function(set1, set2) {
elements <- sort(unique(c(set1$elements, set2$elements)))
return(set(elements))
}

# Define the intersection function for sets


intersection.set <- function(set1, set2) {
elements <- intersect(set1$elements, set2$elements)
return(set(elements))
}

# Define the complementation function for sets


complement.set <- function(set1, universe) {
elements <- setdiff(universe$elements, set1$elements)

©Department of CSE (DS), RNSIT, Bengaluru. 34 / 36


21CSL483: R PROGRAMMING Laboratory

return(set(elements))
}
# Create sets
omega <- set(1:10)
subset1 <- set(c(2, 4, 6, 8))
subset2 <- set(c(4, 6, 8, 10))
universe <- set(1:20)

# Perform union of subsets


subset_union <- union.set(subset1, subset2)
print(subset_union)

# Perform intersection of subsets


subset_intersection <- intersection.set(subset1, subset2)
print(subset_intersection)

# Perform complementation of subset


subset_complement <- complement.set(subset1, universe)
print(subset_complement)

©Department of CSE (DS), RNSIT, Bengaluru. 35 / 36


21CSL483: R PROGRAMMING Laboratory

Viva Questions:
1. What are the main features of R?
2. What is the difference between R and other programming languages?
3. Explain the basics of R programming syntax?
4. How to create variables and assign values in R?
5. Explain the different data types in R and how to handle them?
6. How will you import and export data in R?
7. What is a data frames in R?
8. How will you perform basic statistical analysis in R?
9. What are the different data visualization techniques in R?
10. Explain the concept of packages in R and how to use them?
11. What are the different control structures in R and how to use them?
12. Explain the concept of functions in R and how to write them?
13. Explain the concept of object-oriented programming in R?
14. What are the different classes in R and how to create them?
15. Explain the concept of exception handling in R?
16. Explain the concept of regular expressions in R and how to use them?
17. Explain the concept of time series analysis in R?
18. What is Shiny in R and how to use it for web development?
19. Write a function in R to calculate the mean of a given vector of numbers.
20. How will you create a scatter plot of two given vectors of numeric data in R?
21. How will you create a histogram of a given vector of numeric data in R?
22. How will you generate random numbers from a specified distribution in R?
23. How will you calculate the standard deviation of a given vector of numbers in R?
24. How will you compute the correlation between two given vectors of numeric data in R?
25. How will you create a bar plot of a given vector of categorical data in R?

©Department of CSE (DS), RNSIT, Bengaluru. 36 / 36

You might also like