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

r Lab Manual

The document is a lab manual for R programming that includes various exercises such as checking for leap years, calculating sums, grading students based on marks, creating a simple calculator, searching within a list, and manipulating matrices. It also covers data frame creation, data import from Excel, and performing operations on lists. Each section provides sample code and expected outputs for better understanding.

Uploaded by

sandeep rangari
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)
13 views

r Lab Manual

The document is a lab manual for R programming that includes various exercises such as checking for leap years, calculating sums, grading students based on marks, creating a simple calculator, searching within a list, and manipulating matrices. It also covers data frame creation, data import from Excel, and performing operations on lists. Each section provides sample code and expected outputs for better understanding.

Uploaded by

sandeep rangari
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/ 16

R PROGRAMMING LAB MANUAL

1. Write a program to check whether a year(integer)entered by the user is a leap year or not?
Program:

y = as.numeric(readline(prompt = 'year'))
if ((y %% 4) == 0){
if ((y %% 100) == 0){
if ((y%% 400) ==0){
print(paste(y,'is a leap year'))
}
else {
print(paste(y,"is not a leap year"))
}
}
else{
print(paste(y,"is a leap year"))
}
}else{
print(paste(y,"is not a leap year"))
}

Output:
2. Write an R program to find the sum of natural without formula using the if-else statement and
while loop.
Program:

# take input from the user


num = as.integer(readline(prompt = "Enter a number: "))
if(num < 0) {
print("Enter a positive number")
} else {
sum = 0
# use while loop to iterate until zero
while(num > 0) {
sum = sum + num
num = num - 1
}
print(paste("The sum is", sum))
}

Output:

Enter a number: 10

[1] "The sum is 55"


3. Write a program that prints the grades of the students according to the marks obtained. The
grading of the marks should be as follows. Marks Grades 800-1000 A+, 700 – 800 A, 500 – 700 B+,
400-500 B, 150 – 400 C, Less than 150 D.

Program:

percentage = int ( input ( ‘ Enter your percentage :’ ))


if ( percentage >90 ) {

print (‘A’)
elif ( percentage >80 and percentage <= 90 ):
print (‘B’)

elif ( percentage > 70 and percentage <= 80 ):


print (‘C’)

elif (percentage >= 60 and percentage <= 70):


print (‘D’)
else {
print (‘E’)
}
}
4. Write an R program to make a simple calculator that can add, subtract, multiply and divide using
switch cases and functions.
Program:
Program makes a simple calculator that can add, subtract, multiply and divide using functions
add <- function(x, y) {
return(x + y)
}
subtract <- function(x, y) {
return(x - y)
}
multiply <- function(x, y) {
return(x * y)
}
divide <- function(x, y) {
return(x / y)
}
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = as.integer(readline(prompt="Enter choice[1/2/3/4]: "))
num1 = as.integer(readline(prompt="Enter first number: "))
num2 = as.integer(readline(prompt="Enter second number: "))
operator <- switch(choice,"+","-","*","/")
result <- switch(choice, add(num1, num2), subtract(num1, num2), multiply(num1, num2), divide(
num1, num2))
print(paste(num1, operator, num2, "=", result))

Output
[1] "Select operation."
[1] "1.Add"
[1] "2.Subtract"
[1] "3.Multiply"
[1] "4.Divide"
Enter choice[1/2/3/4]: 4
Enter first number: 20
Enter second number: 4
[1] "20 / 4 = 5"

5. Write a program to perform searching within a list (1 to 50). If the number is found in the list, print
that the search is successful otherwise print that the number is not in the list.
Program:

list1 <- seq(from=1, to=50, by= 1.5)


print(list1)
i= readline()

if (i %in% list1) {
print("Item is present in the List.")
} else {
print("Item is not present in the List.")
}

Output:
>list1 <- seq(from=1, to=50, by= 1.5)
> print(list1)
[1] 1.0 2.5 4.0 5.5 7.0 8.5 10.0 11.5 13.0 14.5 16.0 17.5 19.0 20.5 22.0 23.5 25.0 26.5
[19] 28.0 29.5 31.0 32.5 34.0 35.5 37.0 38.5 40.0 41.5 43.0 44.5 46.0 47.5 49.0
> i= readline()
43.5
> if (i %in% list1) {
+ print("Item is present in the List.")
+ } else {
+ print("Item is not present in the List.")
+ }
[1] "Item is not present in the List."

6. Create a list and data frame that stores the marks of any three subjects for 10 students. Find out the
total marks, average, maximum marks and minimum marks of every subject.

Program :-
maths <- c(65, 78, 89, 54, 79, 75, 88, 67, 92, 85)
physics <- c(51, 67, 54, 52, 81, 72, 85, 83, 62, 66)
chemistry <- c(34, 65, 54, 55, 65, 75, 89, 57, 87, 63)

subject <- list(maths, physics, chemistry)


subject
max_marks_maths <- max(subject[[1]])
max_marks_maths
max_marks_physics <- max(subject[[2]])
max_marks_physics
max_marks_chemistry <- max(subject[[3]])
max_marks_chemistry
min_marks_maths <- min(subject[[1]])
min_marks_maths
min_marks_physics <- min(subject[[2]])
min_marks_physics
min_marks_chemistry <- min(subject[[3]])
min_marks_chemistry
mean_marks_maths <- mean(subject[[1]])
mean_marks_maths
mean_marks_physics <- mean(subject[[2]])
mean_marks_physics
mean_marks_chemistry <- mean(subject[[3]])
mean_marks_chemistry
total_marks_maths <- sum(subject[[1]])
total_marks_maths
total_marks_physics <- sum(subject[[2]])
total_marks_physics
total_marks_chemistry <- sum(subject[[3]])
total_marks_chemistry
Output:
> maths <- c(65, 78, 89, 54, 79, 75, 88, 67, 92, 85)
> physics <- c(51, 67, 54, 52, 81, 72, 85, 83, 62, 66)
> chemistry <- c(34, 65, 54, 55, 65, 75, 89, 57, 87, 63)
> subject <- list(maths, physics, chemistry)
> subject
[[1]]
[1] 65 78 89 54 79 75 88 67 92 85

[[2]]
[1] 51 67 54 52 81 72 85 83 62 66

[[3]]
[1] 34 65 54 55 65 75 89 57 87 63

> max_marks <- max(subject[[1]])


> max_marks
[1] 92
> max_marks_maths <- max(subject[[1]])
> max_marks_maths
[1] 92
> max_marks_physics <- max(subject[[2]])
> max_marks_physics
[1] 85
> max_marks_chemistry <- max(subject[[3]])
> max_marks_chemistry
[1] 89
> min_marks_maths <- min(subject[[1]])
> min_marks_maths
[1] 54
> min_marks_physics <- min(subject[[2]])
> min_marks_physics
[1] 51
> min_marks_chemistry <- min(subject[[3]])
> min_marks_chemistry
[1] 34
> mean_marks_maths <- mean(subject[[1]])
> mean_marks_maths
[1] 77.2
> mean_marks_physics <- mean(subject[[2]])
> mean_marks_physics
[1] 67.3
> mean_marks_chemistry <- mean(subject[[3]])
> mean_marks_chemistry
[1] 64.4
> total_marks_maths <- sum(subject[[1]])
> total_marks_maths
[1] 772
> total_marks_physics <- sum(subject[[2]])
> total_marks_physics
[1] 673
> total_marks_chemistry <- sum(subject[[3]])
> total_marks_chemistry
[1] 644

7. Write the steps to import data from Excel to CSV files and apply data viewer functions like
rm(),dim(),head(), tail(), sorting, filtering, searching to view few set of rows.
Steps:
Transform an Excel file to a CSV file

 Open your Excel file.


 Click on File > Save as.
 Choose the format .csv.
 Click on Save

carSpeeds <- read.csv(file = 'data/car-speeds.csv')


head(carSpeeds)
tail(carspeeds)
sort(x, decreasing = TRUE)
file.remove('data/car-speeds.csv')

# Create two vectors


data1 <- c(1,2,3,4,5,6)
data2 <- c(60, 18, 12, 13, 14, 19)

# pass these vectors as input to the array.


# 4 rows,2 columns and 3 arrays
result <- array(c(data1, data2), dim = c(4,2,3))
print(result)

8. Write a program to create two 3 X 3 matrices A and B and perform the following operations:
a) Transpose of the matrix.
b) addition.
c) subtraction.

Program:
data <- c(1, 2, 7, 2, 8, 4, 3, 0, 9)
data1 <- c(5, 2, 7, 6, 1, 4, 2, 7, 5)
A <- matrix(data, nrow = 3, ncol = 3)
B <- matrix(data, nrow = 3, ncol = 3)
A_T <- t(A)
print("Matrix A")
print(A)
print(“Matrix B”)
print(B)
print("Transpose of A")
print(A_T)
#Addition of matrix
print(“Addition of two matrices”)
print(A+B)
print(“Subtraction of two matrices”)
print(A-B)
Output
[1] "Matrix A"
> print(A)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 8 0
[3,] 7 4 9
> print("Print B")
[1] "Print B"
> print(B)
[,1] [,2] [,3]
[1,] 5 6 2
[2,] 2 1 7
[3,] 7 4 5
> print("Transpose of A")
[1] "Transpose of A"
> print(A_T)
[,1] [,2] [,3]
[1,] 1 2 7
[2,] 2 8 4
[3,] 3 0 9
> #Addition of matrix
> print("Addition of matrix")
[1] "Addition of matrix"
> print(A+B)
[,1] [,2] [,3]
[1,] 6 8 5
[2,] 4 9 7
[3,] 14 8 14

> print("Subtraction of two matrices")


[1] "Subtraction of two matrices"
> print(A-B)
[,1] [,2] [,3]
[1,] -4 -4 1
[2,] 0 7 -7
[3,] 0 0 4

9. Write an R program to create a list containing strings, numbers, vectors and logical values and do
the
following manipulations over the list.
a. Access the first element in the list
b. Give the names to the elements in the list
c. Add element at some position in the list
d. Remove the element
e. Print the fourth element
f. Update the third element

Program:
list_data = list("Python", "PHP", c(5, 7, 9, 11), TRUE, 125.17, 75.83)
print("Data of the list:")
print(list_data)
#Access first element in the list
list_data[[1]][1]
#Give the names to the element
names(list_data) <- c("Programming Language", "Pages", "A Vector", "Boolean", "Double", "Double"
)
print(list_data)
##Add element at some position in the list
list_data <- append(list_data, "Tuesday", after = 2)
print(list_data)
#Remove the element
list_data[c(1, 3)] = NULL
#Print the fourth element
print(list_data[4])
#Update the third element
list_data[3] <- "updated element"
print(list_data[3])

Output:
[1] "Data of the list:"
> print(list_data)
[[1]]
[1] "Python"

[[2]]
[1] "PHP"

[[3]]
[1] 5 7 9 11

[[4]]
[1] TRUE
[[5]]
[1] 125.17

[[6]]
[1] 75.83

> list_data[[1]][1]
[1] "Python"
> names(list_data) <- c("Programming Language", "Pages", "A Vector", "Boolean", "Double", "Doubl
e")
> print(list_data)
$`Programming Language`
[1] "Python"

$Pages
[1] "PHP"

$`A Vector`
[1] 5 7 9 11

$Boolean
[1] TRUE

$Double
[1] 125.17

$Double
[1] 75.83

> list_data <- append(list_data, "Tuesday")


> print(list_data)
$`Programming Language`
[1] "Python"

$Pages
[1] "PHP"

$`A Vector`
[1] 5 7 9 11

$Boolean
[1] TRUE

$Double
[1] 125.17

$Double
[1] 75.83
[[7]]
[1] "Tuesday"

> list_data[c(1, 3)] = NULL


> print(list_data)
$Pages
[1] "PHP"

$Boolean
[1] TRUE

$Double
[1] 125.17

$Double
[1] 75.83

[[5]]
[1] "Tuesday"

> list_data[4] <- NULL


> print(list_data)
$Pages
[1] "PHP"

$Boolean
[1] TRUE

$Double
[1] 125.17

[[4]]
[1] "Tuesday"

> print(list_data[4])
[[1]]
[1] "Tuesday"

> list_data[3] <- "updated element"


> print(list_data[3])
$Double
[1] "updated element"

10. Design a data frame in R for storing about 20 employee details. Create a CSV file named
“input.csv” that defines all the required information about the employee such as id, name, salary,
start_date, dept. Import into R and do the following analysis.
a. Find the total number rows & columns
b. Find the maximum salary
c. Retrieve the details of the employee with maximum salary
d. Retrieve all the employees working in the IT Department
e. Retrieve the employees in the IT Department whose salary is greater than 20000 and write these
details into another file “output.csv”.

data <- read.csv("input.csv")


print(data)
data <- read.csv("input.csv")
print(is.data.frame(data))
#a)number of rows and columns
print(ncol(data))
print(nrow(data))
# b)Get the max salary from data frame.
sal <- max(data$salary)
print(sal)
# c)Get the person detail having max salary.
retval <- subset(data, salary == max(salary))
print(retval)
#d
retval <- subset( data, dept == "IT")
print(retval)
#e
info <- subset(data, salary > 20000 & dept == "IT")
print(info)

11. Create a dataset or table [‘Smart Phone”] in an excel sheet that stores the mobile information
[price, company name, model, Sale Percent] of five different companies. Store at least 20 rows. Write
the scripts and find out the output for the following information.
a. Maximum price of the mobile of each company
b. Minimum price of mobile of each company
c. Average price of mobile of each company
d. Total Price of mobile of each company
Program:

data <- read.csv("record.csv")


print(data)
print(ncol(csv_data))
print(nrow(csv_data))
#a)Maximum price
max_price<- max(csv_data$price)
print(max_price)
#b)Minimum price
min_price<- min(csv_data$price)
print(max_price)
#c)Average price
avg_price <- avg(csv_data$price)
print(avg_price)
#Total price

You might also like