0% found this document useful (0 votes)
15 views31 pages

R Tools LAB

The document contains a series of exercises demonstrating various R programming tasks, including calculating sums, means, and products of vectors, performing random sampling, sorting vectors, and checking for prime numbers. Each exercise includes an aim, code, and output, showcasing the functionality of R through practical examples. The document concludes with exercises on importing and exporting CSV data.

Uploaded by

Sneka ramar
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)
15 views31 pages

R Tools LAB

The document contains a series of exercises demonstrating various R programming tasks, including calculating sums, means, and products of vectors, performing random sampling, sorting vectors, and checking for prime numbers. Each exercise includes an aim, code, and output, showcasing the functionality of R through practical examples. The document concludes with exercises on importing and exporting CSV data.

Uploaded by

Sneka ramar
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/ 31

EX.

NO:1
DATE:- 23-01-24
Find the sum product and mean of vector in r tools

How to find the Sum, Mean, and Product of a Vector

AIM:- To find Sum, Mean, and Product of a Vector.

ALGORITHM
STEP 1: Use the built-in functions
STEP 2: Call sum() with vector and na.rm = TRUE as argument
STEP 3: Call mean() with vector and na.rm = TRUE as argument
STEP 4: Call prod() with vector and na.rm = TRUE as argument
STEP 5: Print the result of each function

R Source Code

A = c(30, NULL, 40, 20, NA)


print("Sum is:")
#ignore NA and NaN values
print(sum(A, na.rm=TRUE))
print("Mean is:")
print(mean(A, na.rm=TRUE))
print("Product is:")
print(prod(A, na.rm=TRUE))

OUTPUT
[1] "Sum is:"
[1] 90
[1] "Mean is:"
[1] 30
[1] "Product is:"
[1] 24000

Result:- We obtain the result successfully.

1
EX.NO:2
DATE:- 24-01-24
R program to sample from a population

A vector of ages of people in a community and you want to randomly select 5 ages for a survey.

AIM:- to find the sample from a population

CODE:-

# Create a vector of ages


ages <- c(25, 30, 35, 40, 45, 50, 55, 60, 65, 70)
# Perform simple random sampling of 5 ages
sampled_ages <- sample(ages, size = 5, replace = FALSE)
# Print the sampled ages
print(sampled_ages)

Output:
[1] 25 40 55 45 70

Result:- We obtain the result successfully.

2
# Create a list of favorite colors
favorite_colors <- list("Red", "Blue", "Green", "Yellow", "Purple", "Orange")
# Convert the list into a vector
colors_vector <- unlist(favorite_colors)
# Perform simple random sampling of 2 colors
sampled_colors <- sample(colors_vector, size = 2, replace = FALSE)
# Print the sampled colors
print(sampled_colors)

Output:
[1] "Red" "Green"
# Create a sample data frame
employees <- data.frame(
Name = c("John", "Jane", "Jim", "Jill", "Joe", "Janet"),
Age = c(30, 35, 25, 40, 45, 28),
Salary = c(50000, 60000, 45000, 70000, 80000, 55000))
# Perform simple random sampling of 2 employees
sampled_employees <- employees[sample(nrow(employees), size = 2,
replace = FALSE), ]
# Print the sampled employees
print(sampled_employees)
Output:
Name Age Salary
1 John 30 50000
6 Janet 28 55000

Result:- We obtain the result successfully.

3
EX.NO:3
DATE:- 31-01-24

3. R Program to sort a vector.

AIM:- To sort a vector using R Program.

CODE:-

# Creating a vector
x <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA)
# Calling sort() function
sort(x)

Output:
[1] -8.0 -5.0 -4.0 1.2 3.0 4.0 6.0 7.0 9.0

# Creating a vector
x <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA)
# Calling sort() function
# to print in decreasing order
sort(x, decreasing = TRUE)
# Calling sort() function
# to print NA at the end
sort(x, na.last = TRUE)

Output:
[1] 9.0 7.0 6.0 4.0 3.0 1.2 -4.0 -5.0 -8.0
[1] -8.0 -5.0 -4.0 1.2 3.0 4.0 6.0 7.0 9.0 NA

# Create a character vector


names <- c("Vipul", "Raj", "Singh", "Jhala")
# Sort the vector in alphabetical order
sorted_names <- sort(names)
print(sorted_names)
Output:

[1] "Jhala" "Raj" "Singh" "Vipul"

Result:- We obtain the result successfully.

4
EX.NO:5
DATE:- 06-02-24

4. To combine the matrix using rbind and cbind methords.


AIM:- To combine the matrix using rbind and cbind methords.

CODE:-

x <- c(1, 2, 3)
y <- c("G1", "G2", "G3")

# Bind two vectors by rows


rbind(x, y)
# Bind integer and vector
rbind(2, x)
Output
[,1] [,2] [,3]
x "1" "2" "3"
y "G1" "G2" "G3"
[,1] [,2] [,3]
2 2 2
x 1 2 3

Result:- We obtain the result successfully.

5
EX.NO:6
DATE:- 06-02-24

5. Use seq() to create sequence.

AIM:- Use seq() to create sequence

CODE:-
#Create sequence elements
seq(1:10)
# R Program to illustrate
# the use of seq() Function

# Creating vector using seq()


vec1 <- seq(1, 10, by = 2)

vec1

# R Program to illustrate
# the use of seq() Function

# Creating vector using seq()


vec1 <- seq(from=22,to=44)
vec1
# Using seq() with length.out argument
result_vector <- seq(from = 1, to = 10, length.out = 5)
print(result_vector)
Output:

[1] 1 2 3 4 5 6 7 8 9 10

[1] 1 3 5 7 9

[1] 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

[1] 1.00 3.25 5.50 7.75 10.00

Result:- We obtain the result successfully.

6
EX.NO:7
DATE:- 06-02-24

6 . Write a program to convert table data in to frame data.

AIM:- To write a program to convert table data in to frame data


CODE:-

data_gfg=data.frame(x=c(1,3,5,3,4),
y=c(1,5,1,4,5))

table_gfg=table(data_gfg$x,data_gfg$y)
print("table in use: ")
table_gfg

new_data_gfg=as.data.frame.matrix(table_gfg)
print("converted to dataframe: ")
new_data_gfg

Result:- We obtain the result successfully.

7
EX.NO:8
DATE:- 07-02-24
7. Calculate student mark list and output in its data frame.
AIM:- To calculate student mark list and output in its data frame.

CODE:-
# R program to assign
#grades to a student
# using nested if-else
#Store marks of all the
#subjects in an array
marks <- c(95, 88, 98, 93, 92, 96)
#Max marks will be
#100 * number of subjects
max_marks <- length(marks) * 100
# Initialize student's
#total marks to 0
total <- 0
# Initialize student's
# grade marks to F
grade<- 'F'
#find the sum of the array
total <- sum(marks)
# Calculate the percentage.
percentage <- (total/ max_marks) *100
# Nested if else
if (percentage >= 90) {
grade <- 'A'
} else {
if (percentage >= 80 && percentage <= 89) {
grade <- 'B'
} else {
if (percentage >= 60 && percentage <= 79) {
grade <- 'C'
} else {
if (percentage >= 33 && percentage <= 59) {
grade <- 'D'
} else {
grade <- 'F' } } }}
print(grade)
Output:
[1] "A"

Result:- We obtain the result successfully

8
EX.NO:9
DATE:- 07-02-24

8. R program to check prime number

AIM:= To check prime number in R program.

CODE:-
Find_Prime_No <- function(n1) {
if (n1 == 2) {
return(TRUE)
}
if (n1 <= 1) {
return(FALSE)
}
for (i in 2:(n1-1)) {
if (n1 %% i == 0) {
return(FALSE)
}
}
return(TRUE)
}

numb_1 <- 13

if (Find_Prime_No(numb_1)) {
# Using paste function to include the number in the output
print(paste(numb_1, "is a prime number"))
} else {
print("It is not a prime number")
}
}

Output:

Result:- We obtain the result successfully

9
EX.NO:10
DATE:- 07-02-24

9. R program to check a leap year.

AIM:- To check a leap year in R program.

CODE:-
# Function to check for a leap year
is_leap_year <- function(year) {
if ((year %% 4 == 0 && year %% 100 != 0) || year %% 400 == 0) {
return(TRUE)
} else {
return(FALSE)
}
}

# Input year
input_year <- 2024

# Check if it's a leap year


if (is_leap_year(input_year)) {
print(paste(input_year, "is a leap year."))
} else {
print(paste(input_year, "is not a leap year."))
}

Output:
[1] "2024 is a leap year."

Result:- We obtain the result successfully

10
EX.NO:11
DATE:- 07-02-24

10. R program to check a number is odd or even.

AIM:- To check a number is even or odd using R program.

CODE:-

number <- 15

if (number%%2 == 0) {
print("Number is even")
} else {
print("Number is odd")
}

OUTPUT:-
[1] "Number is odd"

Result:- We obtain the result successfully

EX.NO:12
11
DATE:- 13-02-24

11. R Programme to find the sum of natural numbers.

AIM:- To find the sum of natural numbers using R

CODE:-
sum<-function(n){
if (n<=1){
return(n)
}else{
return(n+sum(n-1))
}
}
sum(7)

OUTPUT :-
[1] 28

Result:- We obtain the result successfully

12
EX.NO:13
DATE:- 13-02-24

12. Convert decimal into binary using Recursion in R.


AIM:- Convert decimal into binary using Recursion in R.

CODE:-

convert_to_binary <- function(decnum) {


if(decnum > 1) {
convert_to_binary(as.integer(decnum/2))
}
cat(decnum %% 2)
}
convert_to_binary(52)

OUTPUT:-
110100

Result:- We obtain the result successfully

13
EX.NO:14
DATE:- 13-02-24

13. R Program to find the factorial of a number using Recursion.


AIM:- R Program to find the factorial of a number using Recursion.

CODE:-

recur_fact <- function(num) {


if(num <= 1) {
return(1)
} else {
return(num * recur_fact(num-1))
}
}

print(paste("The factorial of 5 is",recur_fact (5)))

OUTPUT:-
[1] "The factorial of 5 is 120"

Result:- We obtain the result successfully

14
EX.NO:15
DATE:- 20-02-24
14. R Program to make a simple calculator.(RS)
AIM:- R Program to make a simple calculator.(RS)

CODE:-
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]: "))
n1 = as.integer(readline(prompt="Enter first number: "))
n2 = as.integer(readline(prompt="Enter second number: "))
operator <- switch(choice,"+","-","*","/")
result <- switch(choice, add(n1, n2), subtract(n1, n2), multiply(n1, n2), divide(n1,
n2))
print(paste(n1, operator, n2, "=", result))
OUTPUT:-
[1] "Select operation."
[1] "1.Add"
[1] "2.Subtract"
[1] "3.Multiply"

15
[1] "4.Divide"
Enter choice[1/2/3/4]: 4
Enter first number: 40
Enter second number: 2
[1] "40/ 2 = 20"

16
EX.NO:16
DATE:- 20-02-24

15. Write a R Program to import CSV data into R.(RS)


AIM:- To write a R Program to import CSV data into R.(RS)

CODE:-

In Environment click Import Dataset

In the dropdown menu, select the From Text (readr)... option. This will open a file explorer.

Click on the Browse button and navigate to your CSV file in the file explorer, select it, and
click Open.

R Studio will open a data import window. Here, you can tweak how R Studio reads your CSV
file. You can set things like whether the first row contains the column names or the maximum
number of rows to read in.

Once you’ve adjusted the settings to fit your needs, click on the Import button.
Your CSV data will be imported into R Studio as a data frame.

OR
rCopy code
setwd("/path/to/your/directory")

Replace "/path/to/your/directory" with the actual path to your directory.


rCopy code
data <- read.csv("data.csv")
rCopy code
head(data)
View(data)
rCopy code # Remove rows with NA
data <- na.omit(data)
# Replace NA values with 0
data[is.na(data)] <- 0
rCopy code
write.csv(data, "data_modified.csv")

17
EX:2

# specifying the path


path <- "/Users/mallikagupta/Desktop/gfg.csv"

# reading contents of csv file


content <- read.csv(path)
# contents of the csv file
print (content)

OUTPUT:-
Output:

ID Name Post Age


1 5 H CA 67
2 6 K SDE 39
3 7 Z Admin 28

EX.NO:17
18
DATE:- 20-02-24

16. Write a R Program to move the result data from R to CSV.


AIM:- To . write a R Program to move the result data from R to CSV.

CODE:-

product Price

computer 800

monitor 450

keyboard 100

printer 150

CODE:-

df <- data.frame(product = c("computer", "monitor", "keyboard",


"printer"),
price = c(800, 450, 100, 150)
)

print(df)

write.csv(DataFrame Name, "Path to export the DataFrame\\File


Name.csv", row.names=FALSE)

df <- data.frame(product = c("computer", "monitor", "keyboard",


"printer"),
price = c(800, 450, 100, 150)
)

write.csv(df, "C:\\Users\\Ron\\Desktop\\Test\\my_products.csv",
row.names=FALSE)

OUTPUT :-

19
product price
1 computer 800
2 monitor 450
3 keyboard 100
4 printer 150

EX.NO:18
DATE:- 20-02-24

17. Draw the Line Graph for Students Data.


AIM:- Draw the Line Graph for Students Data.
CODE:-
Student mark
Vec <- c(71,37,28,39,41) #Create the data for the chart
plot(Vec,type = "o" , xlab = "Papers", ylab = "Marks", main = "Students marks in
one test")

OUTPUT:-

20
EX.NO:19
DATE:- 21-02-24

18. Draw a Pie-Chart for Employee Data.


AIM:- Draw a Pie-Chart for Employee DAata.

CODE:-

expenditure <- c(60000, 30000, 15000, 10000, 12000)

result <- pie(expenditure,


main = "Monthly Payment",
labels = c("Manager", "Asst.Manager", "Superaviser", "Others",
"Clerk"),
col = c("red", "orange", "yellow", "blue", "green")
21
)

print(result)

OUTPUT:-

EX.NO:20
DATE:- 21-02-24

19. Create a Table from the existing data set in R and draw the chart.
AIM:- Create a Table from the existing data set in R and draw the chart

CODE:-
#make this example reproducible
set.seed(1)

#define data
df <- data.frame(team=rep(c('A', 'B', 'C', 'D'), each=4),
pos=rep(c('G', 'F'), times=8),
points=round(runif(16, 4, 20),0))

22
#view head of data
head(df)

#create table with 'position' as rows and 'team' as columns


tab1 <- table(df$pos, df$team)
tab1

barplot(table(mtcars$carb), col="green")

OUTPUT:-

team pos points


1 A G 8
2 A F 10
3 A G 13
4 A F 19
5 B G 7
6 B F 18

ABCD
F2222
G2222

23
EX.NO:21
DATE:- 23-02-24

20. Apply K-Means Algorithm for IRIS data set and output it in graph.
AIM:- Apply K-Means Algorithm for IRIS data set and output it in graph.

CODE:-
# Installing Packages
#install.packages("ClusterR")
#install.packages("cluster")

# Loading package
library(ClusterR)
library(cluster)

# Removing initial label of


# Species from original dataset
24
iris_1 <- iris[, -5]

# Fitting K-Means clustering Model


# to training dataset
set.seed(240) # Setting seed
kmeans.re <- kmeans(iris_1, centers = 3, nstart = 20)
kmeans.re

# Cluster identification for


# each observation
kmeans.re$cluster

# Confusion Matrix
cm <- table(iris$Species, kmeans.re$cluster)
cm

# Model Evaluation and visualization


plot(iris_1[c("Sepal.Length", "Sepal.Width")])
plot(iris_1[c("Sepal.Length", "Sepal.Width")],
col = kmeans.re$cluster)
plot(iris_1[c("Sepal.Length", "Sepal.Width")],
col = kmeans.re$cluster,
main = "K-means with 3 clusters")

## Plotiing cluster centers


kmeans.re$centers
kmeans.re$centers[, c("Sepal.Length", "Sepal.Width")]

# cex is font size, pch is symbol


points(kmeans.re$centers[, c("Sepal.Length", "Sepal.Width")],
col = 1:3, pch = 8, cex = 3)

## Visualizing clusters
y_kmeans <- kmeans.re$cluster
clusplot(iris_1[, c("Sepal.Length", "Sepal.Width")],
y_kmeans,
lines = 0,
shade = TRUE,
color = TRUE,
labels = 2,
25
plotchar = FALSE,
span = TRUE,
main = paste("Cluster iris"),
xlab = 'Sepal.Length',
ylab = 'Sepal.Width')

OUTPUT:-
K-means clustering with 3 clusters of sizes 50, 62, 38

Cluster means:
Sepal.Length Sepal.Width Petal.Length Petal.Width
1 5.006000 3.428000 1.462000 0.246000
2 5.901613 2.748387 4.393548 1.433871
3 6.850000 3.073684 5.742105 2.071053

Clustering vector:
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1
[38] 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2
[75] 2 2 2 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 2 3 3 3 3 2 3 3 3
3
[112] 3 3 2 2 3 3 3 3 2 3 2 3 2 3 3 2 2 3 3 3 3 3 2 3 3 3 3 2 3 3 3 2 3 3 3 2
3
[149] 3 2

Within cluster sum of squares by cluster:


[1] 15.15100 39.82097 23.87947
(between_SS / total_SS = 88.4 %)

Available components:

[1] "cluster" "centers" "totss" "withinss" "tot.withinss"


[6] "betweenss" "size" "iter" "ifault"

26
> kmeans.re$cluster
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1
[38] 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2
[75] 2 2 2 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 2 3 3 3 3 2 3 3 3
3
[112] 3 3 2 2 3 3 3 3 2 3 2 3 2 3 3 2 2 3 3 3 3 3 2 3 3 3 3 2 3 3 3 2 3 3 3 2
3
[149] 3 2
> cm <- table(iris$Species, kmeans.re$cluster)
> cm
1 2 3
setosa 50 0 0
versicolor 0 48 2
virginica 0 14 36
> kmeans.re$centers
Sepal.Length Sepal.Width Petal.Length Petal.Width
1 5.006000 3.428000 1.462000 0.246000
2 5.901613 2.748387 4.393548 1.433871
3 6.850000 3.073684 5.742105 2.071053
> kmeans.re$centers[, c("Sepal.Length", "Sepal.Width")]
Sepal.Length Sepal.Width
1 5.006000 3.428000
2 5.901613 2.748387
3 6.850000 3.073684

27
EX.NO:22
DATE:- 27-02-24

21. Get some input from mtcar data set and perform analysis.
AIM:- Get some input from mtcar data set and perform analysis.

CODE:-

#view first six rows of mtcars dataset

28
head(mtcars)

mpg cyl disp hp drat wt qsec vs am gear carb


Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

#summarize mtcars dataset


summary(mtcars)
#display rows and columns
dim(mtcars)
#display column names
names(mtcars)
#create histogram of values for mpg
hist(mtcars$mpg,
col='steelblue',
main='Histogram',
xlab='mpg',
ylab='Frequency')

OUTPUT:-
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1

29
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

> summary(mtcars)
mpg cyl disp hp
Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0
1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5
Median :19.20 Median :6.000 Median :196.3 Median :123.0
Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7
3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0
Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0
drat wt qsec vs
Min. :2.760 Min. :1.513 Min. :14.50 Min. :0.0000
1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000
Median :3.695 Median :3.325 Median :17.71 Median :0.0000
Mean :3.597 Mean :3.217 Mean :17.85 Mean :0.4375
3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000
Max. :4.930 Max. :5.424 Max. :22.90 Max. :1.0000
am gear carb
Min. :0.0000 Min. :3.000 Min. :1.000
1st Qu.:0.0000 1st Qu.:3.000 1st Qu.:2.000
Median :0.0000 Median :4.000 Median :2.000
Mean :0.4062 Mean :3.688 Mean :2.812
3rd Qu.:1.0000 3rd Qu.:4.000 3rd Qu.:4.000
Max. :1.0000 Max. :5.000 Max. :8.000
> #display rows and columns
> dim(mtcars)
[1] 32 11
> #display column names
> names(mtcars)
[1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear"
[11] "carb"
> #create histogram of values for mpg
> hist(mtcars$mpg,
+ col='steelblue',
+ main='Histogram',
+ xlab='mpg',
+ ylab='Frequency')
>

30
31

You might also like