Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views22 pages

R Labmanual

R_labmanual

Uploaded by

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

R Labmanual

R_labmanual

Uploaded by

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

IMPACT COLLEGE OF ENGINEERING &APPLIEDSCIENCE

KodigehalliPost,Bangalore –560092

“LABORATORY MANNUAL”
“R PROGRAMMING”

(21CSL483)
As per VTU RevisedSyllabus

Compiledby:
Mrs.SUVARNA Dr.DHANANJAYAV
Asst.Professor, Head of Department
Dept. of CS & E Dept.of CS& E

Name:

DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING

2023-2024
Installation guide for R and RStudio

Step 1 – Install R

1. Download the R installer from https://cran.r-•‐project.org/

2. Run the installer. Default settings are fine. If you do not have admin rights on your laptop, then ask
you local IT support. In that case, it is important that you also ask them to give you full
permissions to the R directories. Without this, you will not be able to install additional packages
later.

Step 2 – Install RStudio


1. Download RStudio: https://www.rstudio.com/products/rstudio/download/

2. Once the installation of R has completed successfully (and not before), run the RStudio
installer.
3. If you do not have administrative rights on your laptop, step 2 may fail. Ask your IT Support
or download a pre-•‐built zip archive of RStudio which doesn’t need installing. The link for this
is towards the bottom of the download page, highlighted in Image 2.

a. Download the appropriate archive for your system (Windows/Linux only – the Mac version
can be installed into your personal “Applications” folder without admin rights).

b. Double clicking on the zip archive should automatically unpack it on most Windows
machines.

Step 3 – Check that R and RStudio are working


1. Open RStudio. It should open a window that looks similar to image 3 below.

2. In the left hand window, by the ‘>’sign, type ‘4+5’(without the quotes) and hit enter. An outputline
reading ‘[1] 9’ should appear. This means that R and RStudio are working.

3. If this is not successful, contact us or your local IT support for further advice

Figure 3. Running R with RStudio

Step 4 – Install R packages required for the workshop


1. Click on the tab ‘ Packages’ then ‘Install’ as shown in Image 4. Or Tools -•‐>
Install packages.
2. Install the following packages: mixOmics version 6.1.0, mvtnorm, RColorBrewer,
corrplot, igraph (see Image 4). For apple mac users, if youare unable to install the
mixOmics imported library rgl, you will need to install the XQuartz software first
https://www.xquartz.org/
3. Check that the packages are installed by typing ‘library(mixOmics)’ (without thequotes) in
the prompt and press enter (see Image 5).
4. Then type ‘sessionInfo()’ and check that mixOmics version 6.1.0 has been installed(image
6).

Figure 4. Click on Install to install R packages.

Figure 5. Specify the list of packages to be installed


R PROGRAMMING LABORATORY(21CSL483)

Figure 6. Check that the package mixOmics is installed and has the version 6.1.0.

Suvarna Hugar, Asst.Prof, ICEAS Page 5


R PROGRAMMING LABORATORY(21CSL483)

AIM : MODULE 1 :

Program1: Program to find the L.C.M. of two input number using R.

lcm <- function(x, y) {


# choose the greater number
if(x > y) {
greater = x
} else {
greater = y
}

while(TRUE) {
if((greater %% x == 0) && (greater %% y == 0)) {
lcm = greater
break
}
greater = greater + 1
}
return(lcm)
}

# take input from the user


num1 = as.integer(readline(prompt="Enter first number: "))
num2 = as.integer(readline(prompt="Enter second number: "))

print(paste("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2)))

Output:

Enter first number: 24


Enter second number: 25
[1] "The L.C.M. of 24 and 25 is 600"

Suvarna Hugar, Asst.Prof, ICEAS Page 6


R PROGRAMMING LABORATORY(21CSL483)

Program 2 : R program to check if the input number is odd or even.

# Program to check if the input number is odd or even.

# A number is even if division by 2 give a remainder of 0.

# If remainder is 1, it is odd.

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

if((num %% 2) == 0) {

print(paste(num,"is Even"))

} else {

print(paste(num,"is Odd"))

Output:

Enter a number: 89
[1] "89 is Odd"

Suvarna Hugar, Asst.Prof, ICEAS Page 7


R PROGRAMMING LABORATORY(21CSL483)

AIM : MODULE 2

Program 1 : R Program to check a number is palindrome or not.


n <- readline(prompt="Enter a four digit number please: ")

n <- as.integer(n)

num<-n

rev<-0

while(n!=0){

rem<-n%%10

rev<-rem+(rev*10)

n<-as.integer(n/10)

print(rev)

if(rev==num){

cat(num,"is a palindrome num")

}else{

cat(num,"is not a palindrome number")

Output:

Suvarna Hugar, Asst.Prof, ICEAS Page 8


R PROGRAMMING LABORATORY(21CSL483)

Program 2 : R program to add two matrices:

# Creating 1st Matrix

B = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)

# Creating 2nd Matrix

C = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3)

# Getting number of rows and columns

num_of_rows = nrow(B)

num_of_cols = ncol(B)

# Creating matrix to store results

sum = matrix(, nrow = num_of_rows, ncol = num_of_cols)

# Printing Original matrices

print(B)

print(C)

Suvarna Hugar, Asst.Prof, ICEAS Page 9


R PROGRAMMING LABORATORY(21CSL483)

AIM: Module 3

Program1 : Write a R program to create a Dataframes which contain


details of 5 employees and display the details.
emp.data<- data.frame(

employee_id = c (1:5),

employee_name = c("Shubham","Arpita","Nishka","Gunjan","Sumit"),

sal = c(623.3,915.2,611.0,729.0,843.25),

starting_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11",

"2015-03-27")),

stringsAsFactors = FALSE

# Printing the data frame.

print(emp.data)

OUTPUT:

# Printing the data frame.

> print(emp.data)

employee_id employee_name sal starting_date

1 1 Shubham 623.30 2012-01-01

2 2 Arpita 915.20 2013-09-23

3 3 Nishka 611.00 2014-11-15

4 4 Gunjan 729.00 2014-05-11

5 5 Sumit 843.25 2015-03-27

Suvarna Hugar, Asst.Prof, ICEAS Page 10


R PROGRAMMING LABORATORY(21CSL483)

Program 2: Write a program to demonstrate various list methods in R.


# Creating a list containing a vector, a matrix and a list.

list_data <- list(c("Shubham","Arpita","Nishka"), matrix(c(40,80,60,70,90,80), nrow = 2),

list("BCA","MCA","B.tech"))

# Giving names to the elements in the list.

names(list_data) <- c("Student", "Marks", "Course")

# Adding element at the end of the list.

list_data[4] <- "Moradabad"

print(list_data[4])

# Removing the last element.

list_data[4] <- NULL

# Printing the 4th Element.

print(list_data[4])

# Updating the 3rd Element.

list_data[3] <- "Masters of computer applications"

print(list_data[3])

OUTPUT:

[[1]]
[1] "Moradabad"

$<NA>
NULL

$Course
[1] "Masters of computer applications"

Suvarna Hugar, Asst.Prof, ICEAS Page 11


R PROGRAMMING LABORATORY(21CSL483)

AIM : MODULE 4

Program 1: R program to calculate area and perimeter of a rectangle.

Rectangle = function(length, width){


area = length * width
perimeter = 2 * (length + width)

# create an object called result which


is # a list of area and perimeter
result = list("Area" = area, "Perimeter" =
perimeter) return(result)
}

resultList = Rectangle(2, 3)
print(resultList["Area"])
print(resultList["Perimeter"])

OUTPUT:

Suvarna Hugar, Asst.Prof, ICEAS Page 12


R PROGRAMMING LABORATORY(21CSL483)

Program 2: R Program to find the sum of squares of a given series of


numbers.
sum_series <- function(vec){

if(length(vec)<=1)

return(vec^2)

else

return(vec[1]^2+sum_series(vec[-1]))

}
series <- c(1:10)

sum_series(series)

Suvarna Hugar, Asst.Prof, ICEAS Page 13


R PROGRAMMING LABORATORY(21CSL483)

AIM: MODULE 5

Program 1: R program for Data Manipulation in R With dplyr Package.


To install the dplyr package, run the following command:
install.packages("dplyr")
#To load dplyr package
library("dplyr")
#To load datasets package
library("datasets")
#To load iris dataset
data(iris)
summary(iris)
OUTPUT:

Following are some of the important functions included in the dplyr package
select() :- To select columns (variables)
filter() :-To filter (subset) rows.
mutate() :-To create new variables
summarise() :- To summarize (or aggregate) data
group_by() :- To group data
arrange() :- To sort data
join() :- To join data frames.
SELECT():
#To select the following columns
selected <- select(iris, Sepal.Length, Sepal.Width,
Petal.Length)

Suvarna Hugar, Asst.Prof, ICEAS Page 14


R PROGRAMMING LABORATORY(21CSL483)

head(selected)
#To select all columns from Sepal.Length to Petal.Length
selected1 <- select(iris, Sepal.Length:Petal.Length)
#To print first four rows
head(selected1, 4)
#To select columns with numeric indexes
selected1 <- select(iris,c(3:5))
head(selected1)
OUTPUT:

Suvarna Hugar, Asst.Prof, ICEAS Page 15


R PROGRAMMING LABORATORY(21CSL483)

(2) Filter()

It is used to find rows with matching criteria. It also works like the select() function, i.e., we
pass a data frame along with a condition separated by a comma.
For example:
#To select the first 3 rows with Species as
setosa filtered <- filter(iris, Species == "setosa"
)
OUTPUT:

(3) Mutate()

It creates new columns and preserves the existing columns in a dataset.


For example:
#To create a column “Greater.Half” which stores TRUE if given condition
is TRUE
col1 <- mutate(iris, Greater.Half = Sepal.Width > 0.5 * Sepal.Length)
tail(col1)
OUTPUT:

Suvarna Hugar, Asst.Prof, ICEAS Page 16


R PROGRAMMING LABORATORY(21CSL483)

Program 2: Program for Debugging in R Programming


traceback() Function
The traceback() function is used to give all the information on how your function arrived
at an error. It will display all the functions called before the error arrived called the “call
stack” in many languages, R favors calling traceback.

# Function 1

function_1 <- function(a){

a+5

# Function 2

function_2 <- function(b) {

function_1(b)

# Calling function

function_2("s")

# Call traceback()

traceback()

OUTPUT:
2: function_1(b) at #1
1: function_2("s")

Suvarna Hugar, Asst.Prof, ICEAS Page 17


R PROGRAMMING LABORATORY(21CSL483)
MODULE 6
6a) R program to implement Linear Search:
binarySearch = function(arr,item) {
low <- 1; high <- length(arr)
while (low <= high){
mid <- as.integer(round((low + high) / 2))
if (abs(arr[mid] - item) ==0) {
return(mid)
} else if (arr[mid] < item) {
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, "\nSorted array ",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")
}
Output:
Array 4 0 3 1 5 6 2
Sorted array 0 1 2 3 4 5 6
item = 4
Element is present at index 5

Suvarna Hugar, Asst.Prof, ICEAS Page 18


R PROGRAMMING LABORATORY(21CSL483)

6B) R Program to Print nth Fibonacci number

fib <- function(n) {

if (n <= 0) {

return(0)

} else if (n == 1) {

return(1)

} else {

return(fib(n - 1) + fib(n - 2))

n <- 10

for (i in 1:n) {

print(fib(i))

7a) R program to implement BubbleSort Algorithm:


bubble_sort <- function(x)
{
n <- length(x)
for (i in 1 : (n - 1)) {

for (j in 1 : (n - i)) {
if (x[j] > x[j + 1]) {
temp <- x[j]
x[j] <- x[j + 1]
x[j + 1] <- temp
}
}
}
x
}

arr <- sample(1 : 100, 10)

sorted_array <- bubble_sort(arr)


sorted_array
OUTPUT:

[1] 2 19 26 68 74 76 80 81 82 91

Suvarna Hugar, Asst.Prof, ICEAS Page 19


R PROGRAMMING LABORATORY(21CSL483)

LAB PROGRAMS
MODULE 1
A. Program to find the L.C.M. of two input number using R.
B. R program to check if the input number is odd or even.

MODULE 2:

A. R Program to check a number is palindrome or not.


B. R program to add two matrices:

MODULE 3:

A. Write a R program to create a Dataframes which contain details of 5 employees and display the
details.
B. Write a program to demonstrate various list methods in R.

MODULE 4:

A. R program to calculate area and perimeter of a rectangle.


B. R Program to find the sum of squares of a given series of numbers.

MODULE 5:

A. R program for Data Manipulation in R With dplyr Package.


B. Program for Debugging in R Programming.

MODULE 6:
A. R program to implement Linear Search:
B. R Program to Print nth Fibonacci number

MODULE 7

A. R program to implement Bubble Sort Algorithm:


B. Program to find the HCF of two input number using R

Suvarna Hugar, Asst.Prof, ICEAS Page 20


R PROGRAMMING LABORATORY(21CSL483)

VIVA QUESTIONS:
1) What is R (programming Language)?
2) What are the main features of R?
3) What is the difference between R and other programming languages?
4) Can you explain the basics of R programming syntax?
5) How can you create variables and assign values in R?
6) How can you import and export data in R?
7) Explain the concept of data frames in R?
8) Compare R & Python.
9) What is difference between matrix and data frames?
10) Differentiate between vector, List, Matrix, and Data frame.

Suvarna Hugar, Asst.Prof, ICEAS Page 21


R PROGRAMMING LABORATORY(21CSL483)

Suvarna Hugar, Asst.Prof, ICEAS Page 22

You might also like