R - Lab Manual (2022-23)
R - Lab Manual (2022-23)
R - Lab Manual (2022-23)
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:
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
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.
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
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
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
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
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"
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:
Output:
Output:
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
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
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
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)
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.
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)
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
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
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)
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] "" "" "" "" ""
Module 2
1. Write a program to get all prime numbers up to a given number (based on the
sieve of Eratosthenes)
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)
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":
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")
Output:
> x <- matrix()
> if (is.matrix(x)){ print('Is a Matrix')
+ }else{
+ print("Not a Matrix")
+ }
[1] "Is a Matrix"
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
a2 <- c(6, 3, 2)
a3 <- c(5, 2, 4)
Output:
> # determinant of matrix
> print(det(A))
[1] -28
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:
Module 3
df <- data.frame(
Training = c("Strength", "Stamina", "other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
Output:
> print(df)
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 other 120 45
df <- data.frame(
Training = c("Strength", "Stamina", "other"),
©Department of CSE (DS), RNSIT, Bengaluru. 20 / 36
21CSL483: R PROGRAMMING Laboratory
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:
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)
)
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
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
apply(X, 2, sum)
Output:
> apply(X, 2, sum)
[1] 3 7 11
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
[[4]]
[1] TRUE
print(my_list[1])
Output:
> print(my_list[1])
[[1]]
[1] "Hello"
$age
[1] 30
Module 4
# 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
# 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)
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)
}
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)
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?