[go: up one dir, main page]

0% found this document useful (0 votes)
11 views34 pages

BDA Lab Record

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)
11 views34 pages

BDA Lab Record

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/ 34

21311A05L9 Kalyan.

1. R Environment setup: Installation of R and RStudio in Windows

Here are the steps to install R and RStudio in Windows:


Step 1: Install R
1. Go to the CRAN (Comprehensive R Archive Network) website at https://cran.r-
project.org/bin/windows/base/
2. Click on the "Download R for Windows" link.
3. Click on the "install R for the first time" link.
4. Click on the "Download R 4.2.2 for Windows" link
5. Click on the "Save File" button.
6. Double-click on the downloaded file to start the installation process.
7. Follow the installation wizard's instructions to complete the installation.
Step 2: Install RStudio
1. Go to the RStudio website at
https://www.rstudio.com/products/rstudio/download/#download
2. Click on the "Download" button under RStudio Desktop.
3. Select the appropriate installer for your operating system (Windows in this case).
4. Click on the "Download" button.
5. Double-click on the downloaded file to start the installation process.
6. Follow the installation wizard's instructions to complete the installation.
Step 3: Launch RStudio
1. Open RStudio by clicking on the RStudio icon on your desktop.
2. RStudio should automatically detect the location of your R installation. If not, click on
the "Tools" menu, then "Global Options", then "General", and enter the path to your R
installation in the "R Home Directory" field.
3. You should now be ready to use R and RStudio on your Windows machine.

1
21311A05L9 Kalyan. K

2. Write R commands for


i) Variable declaration and Retrieving the value of the stored Variables

Exp1: Declare and retrieve the value of a numeric variable:


# Declare a variable called "my_num" and assign it the value 42 my_num<- 42
# Retrieve the value of "my_num" and print it to the console print(my_num)
Output: [1] 42

Exp2: Declare and retrieve the value of a character variable:


# Declare a variable called "my_string" and assign it the value "Hello, world!"
my_string<- "Hello, world!"
# Retrieve the value of "my_string" and print it to the console
print(my_string)
Output: [1] "Hello, world!"

Exp3: Declare and retrieve the value of a Boolean variable:


# Declare a variable called "my_bool" and assign it the value TRUE
my_bool<- TRUE
# Retrieve the value of "my_bool" and print it to the console
print(my_bool)
Output: [1] TRUE

Exp4: Declare and retrieve the value of a vector variable:


# Declare a variable called "my_vec" and assign it a vector of values
my_vec<- c(1, 2, 3, 4)
# Retrieve the value of "my_vec" and print it to the console
print(my_vec)
Output: [1] 1 2 3 4

2
21311A05L9 Kalyan. K

ii) Write an R script with comments (Example: Addition of Two Numbers)


# Define the two numbers to be added
num1 <- 10
num2 <- 5
# Add the two numbers together and store the “result” in a new variable
result <- num1 + num2
# Print the “result” to the console print(result)
Output: [1] 15

iii) Type of a variable using class () Function.

Exp 1: Numeric variable


num_var<- 10
print(class(num_var))
Output: "numeric"
Exp 2: Character variable
char_var<- "Hello, world!"
print(class(char_var))
Output: "character"
Exp 3: Boolean variable
bool_var<- TRUE
print(class(bool_var))
Output: "logical"
Exp 4: Vector variable
vec_var<- c(1, 2, 3, 4)
print(class(vec_var))
Output: "numeric"

3
21311A05L9 Kalyan. K

3. Write R command to

i) Illustrate summation, subtraction, multiplication, and Division operations on


vectors using vectors.

Exp 1: Vector addition


vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)
result <- vec1 + vec2
print(result)
Output: 5 7 9

Exp 2: Vector subtraction


vec3 <- c(10, 20, 30)
vec4 <- c(3, 6, 9)
result <- vec3 - vec4
print(result)
Output: 7 14 21

Exp 3: Vector multiplication


vec5 <- c(2, 4, 6)
vec6 <- c(3, 2, 1)
result <- vec5 * vec6
print(result)
Output: 6 8 6

Exp 4: Vector division


vec7 <- c(10, 20, 30)
vec8 <- c(5, 2, 3)
result <- vec7 / vec8
print(result)
Output: 2 10 10

4
21311A05L9 Kalyan. K

ii) Enumerate multiplication and division operations between matrices and


vectors in R console

Exp1: 3x3 matrix X 3x1 vector = 3x1

# Define a 3x3 matrix


A <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol=3)
# Define a vector
x <- c(1, 2, 3)

# Multiply the matrix and the vector


Ax <- A %*% x
# Print the result
print(Ax)
Output: 30 36 42

Exp2: 2x3 matrix X 3x1 vector = 2x1

# Define a 2x3 matrix


A <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol=3)
# Define a vector
x <- c(1, 2, 3)

# Multiply the matrix and the vector


Ax <- A %*% x
# Print the result
print(Ax)
Output: 22 28

Exp3: 2x2 matrix X 2x1 vector = 2x1

# Define a 2x2 matrix


A <- matrix(c(1, 2, 3, 4), nrow = 2, ncol=2)
# Define a vector
x <- c(1, 2)
# Multiply the matrix and the vector
Ax <- A %*% x
# Print the result
print(Ax)
Output:7 10

5
21311A05L9 Kalyan. K

Exp4: # 1x3 vector and a 3x3 matrix = 1x3

A <- c(1, 2, 3)
B <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3)
# Multiply vector A by matrix B
C <- A %*% B
# Output the result C
Output: 14 32 50

Exp5: # Define a 1x3 row vector and a 3x2 matrix = 1x2

A <- c(1, 2, 3)
B <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 3, ncol = 2)
# Multiply row vector B by matrix A
C <- A %*% B
# Output the result C
Output:14 32

Exp6: # 1x2 vector and a 2x2 matrix = 1x2

A <- c(1, 2)
B <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2)
# Multiply vector A by matrix B
C <- A %*% B
# Output the result C
Output: 5 11

Exp7: # 1x2 vector and a 2x3 matrix = 1x3

A <- c(1, 2)
B <- matrix(c(1, 2, 3, 4,5,6), nrow = 2, ncol = 3)
# Multiply vector A by matrix B
C <- A %*% B
# Output the result C
Output: 5 11 17

Exp8: Dividing a matrix by a scalar using / operator:

# Define a 2x2 matrix and a scalar value


A <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2)
B <- 2

6
21311A05L9 Kalyan. K

# Divide matrix A by scalar B


C <- A / B
# Output the result C
Output:

[,1] [,2]

[1,] 0.5 1.5

[2,] 1.0 2.0

Exp9: 3x3 matrix / 3x1 vector

# Define a 3x3 matrix


A <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol=3)
# Define a vector
x <- c(1, 2, 3)
# Divide the matrix and the vector
D <- A / x
# Print the result D
Output:

Exp10: # Multiplying a matrix by a scalar using * operator:

# Define a 2x2 matrix and a scalar value


A <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2)
B <- 2
# Multiply matrix A by scalar B
C <- A * B
# Output the result C
Output:

2 6

4 8

7
21311A05L9 Kalyan. K

4. Write R command to

i) illustrates the usage of Vector sub setting& Matrix sub setting

Vector sub setting examples:

Example 1: Subset a vector using logical indexing

v <- c(1, 2, 3, 4, 5)
v[v > 3]
Output: 4 5

Example 2: Subset a vector using logical indexing

v <- c(1, 2, 3, 4, 5)
v[v < 3]
Output: 1 2

Example 3: Subset a vector using integer indexing

v <- c(1, 2, 3, 4, 5)
v[c(1, 3, 5)]
Output: 1 3 5

Example 4: Subset a vector using negative integer indexing

v <- c(1, 2, 3, 4, 5)
v[-c(2, 4)]
Output: 1 3 5

Example 5: Subset a vector using named indexing

v <- c(apple = 1, banana = 2, cherry = 3, durian = 4, elderberry = 5)


v[c("banana", "durian")]
Output: 2 4

Matrix subsetting examples:

Example 1: Subset a matrix using integer indexing

m <- matrix(1:9, nrow = 3, ncol=3)


m[2, 3]

8
21311A05L9 Kalyan. K

Output: 6

Example 2: Subset a matrix using logical indexing

m <- matrix(1:9, nrow = 3, ncol=3)


m[m > 5]
Output: 6 7 8 9

Example 3: Subset a matrix using logical indexing

m <- matrix(1:9, nrow = 3, ncol=3)


m[m < 5]
Output: 1 2 3 4

Example 4: Subset a matrix row using integer indexing

m <- matrix(1:9, nrow = 3, ncol=3)


m[2, ]
Output: 2 5 8

Example 5: Subset a matrix column using integer indexing

m <- matrix(1:9, nrow = 3, ncol=3)


m[, 3]
Output: 7 8 9

ii) Write a program to create an array of 3×3 matrixes with 3 rows


and
3 columns.

Example 1: Using array () function


# Create an array of 3x3 matrices with 3 rows and 3 columns
arr1 <- array (1:27, dim = c(3, 3, 3))
# Print the array
arr1
Output:

9
21311A05L9 Kalyan. K

Example 2:
# Create an array of 3x3 matrices my_array <-
array(0, dim = c(3, 3, 3))
# View the array
my_array
Output:

Example 3: Using matrix() and array() function

# Create a 3x3 matrix


m1 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol=3)

# Create the array of 3x3 matrices


arr1 <- array(m1, dim = c(3, 3, 3)) # Print
the array
arr1

10
21311A05L9 Kalyan. K

# Output:

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

iii) Write a program to create a class, object, and function


# Define a class called "Person"

Person <- setClass("Person", slots = list(name = "character", age = "numeric"))

# Create an object of class "Person"


person1 <- new("Person", name = "Alice", age = 25) person2 <-

new("Person", name = "Bob", age = 30)

# Define a function that operates on objects of class "Person"


get_person_info <- function(person)
{
cat("Name:", person@name, "\n")
cat("Age:", person@age, "\n")
}
# Use the function to print information about the objects we created
get_person_info(person1)

get_person_info(person2)

Output:

Name: Alice Age: 25

Name: Bob Age: 30

11
21311A05L9 Kalyan. K

5. Write a command in R console

i) To create a tshirt_factor, which is ordered with levels ‗S‘,‗M‘, and ‗L‘.

The R command to create a tshirt_factor variable with ordered levels 'S', 'M', and 'L':

tshirt_factor<- factor(c("S", "M", "L"), ordered = TRUE, levels = c("S", "M", "L")) tshirt_factor

Output:

[1] S M L

Levels: S < M < L

ii) Write the command in R console to create a new data frame containing the ‗age‘
parameter from the existing data frame. Check if the result is a data frame or not. Also R
commands for data frame functions cbind(), rbind(), sort()

First create a Data frame with the following data:

Roll No Name Marks


001 Kishore 50
002 Venkat 60
003 Raju 55
004 Laxman 64
005 Vijay 70

Student=data.frame(RollNo= c (001,002,003,004,005), Name=c('Kishore','Venkat', 'Raju', 'Laxman',


'Vijay'), Marks=c(50,60,55,64,70))

Print (Student)

#the student data frame is created

#create a new data frame containing the ‘age’ parameter from the existing data frame.

Student_df=cbind(Student, Age=c(20,21,22,23,24))

Print (Student_df)

12
21311A05L9 Kalyan. K

Output:

Roll No Name Marks Age


001 Kishore 50 20
002 Venkat 60 21
003 Raju 55 22
004 Laxman 64 23
005 Vijay 70 24

#create a new data frame include new row from the existing data frame.

Student_df2=rbind(Student_df, c(006, ‘mounika’,80, 20) print(Student_df2)

Output:

Roll No Name Marks Age


001 Kishore 50 20
002 Venkat 60 21
003 Raju 55 22
004 Laxman 64 23
005 Vijay 70 24
006 Mounika 80 20

# R commands for data frame functions cbind(), rbind(), sort() on Matrices # create

3X3 matrix with following integers

M1= 1 6 7

943

02 4

M1=matrix (c (1,9,0,6,4,2,7,3,4), nrow=3, ncol=3)

print(M1)

# Apply cbind() on M1

M2 = cbind(M1, c(1,2,3))

print(M2)

13
21311A05L9 Kalyan. K

Output:

M2 = 1 6 7 1

9432

0 2 43

# Apply rbind() on M1 M3=

rbind(M1, c(1,2,3))

print(M3) Output:

167

943

0 2 4

12 3

# Apply sort() on M1 sort(M1)

Output:

012344679

14
21311A05L9 Kalyan. K

6. Write R command for


i) Create a list containing strings, numbers, vectors and logical values

my_list <- list("apple", 10, c(1, 2, 3), TRUE)


print(my_list) Output:

[[1]]

[1] "apple" [[2]]

[1] 10

[[3]]

[1] 1 2 3

[[4]]

[1] TRUE

#We can access each element of the list using indexing.

my_list[[1]]

[1]

"apple" my_list[[2]] [1]

10

my_list[[3]] [1] 1 2 3

my_list[[4]]

[1] TRUE

#We can find the length of the list using length()

length(my_list)

[1] 4

15
21311A05L9 Kalyan. K

ii. create a R Command for to create a list containing a vector, a matrix, and a list. Also give
names to the elements in the list and display the list also access the list elements.

my_list <- list(my_vector=c(1, 2, 3), my_matrix=matrix(c(1:9), nrow=3, ncol=3),


my_nested_list=list('a',2,c(1,2,3)))

my_list

#Output:

$my_vector [1]

123

$my_matrix

[,1] [,2] [,3]

[1,] 1 4 7

[2,] 2 5 8

[3,] 3 6 9

$my_nested_list

$my_nested_list

[[1]]

[1] "a"

$my_nested_list

[[2]]

[1] 2

$my_nested_list

[[3]]

[1] 1 2 3

16
21311A05L9 Kalyan. K

iii. To add a new element at the end of the list and delete the element from the middle
display the same

#Create a list

my_list <- list('kishore','ram','laxman','balaji') my_list

#Output:

[[1]]
[1] "kishore"

[[2]]
[1] "ram"

[[3]]
[1]"laxman"

[[4]]
[1] "balaji"

# Add a new element to end of the list

my_list[[length(my_list)+1]]='sunny' my_list

#Output:

[[1]]
[1] "kishore"

[[2]]
[1] "ram"

[[3]]
[1] "laxman"

[[4]]
[1] "balaji"

[[5]]
[1] "sunny"

#Delete an element from the middle of the list

my_list=my_list[-3]

my_list

17
21311A05L9 Kalyan. K

#Output

[[1]]
[1] "kishore"

[[2]]
[1] "ram"

[[3]]
[1] "balaji"

[[4]]
[1] "sunny"

iv. To create two lists, merge two lists. Convert the lists into vectors and perform addition on
the two vectors. Display the resultant vector.

18
21311A05L9 Kalyan. K

Example 2 :

l1=list(1,2,3)

l2=list(4,5,6)

ml=c(l1,l2)

v1=unlist(l1)

v2=unlist(l2)

rv=v1+v2

Rv

Output: [1] 5 7 9

19
21311A05L9 Kalyan. K

7. Write R command for

i) logical operators—AND (&), OR ( | ) and NOT (!).

AND Operator (&):


# Example 1:
x <- TRUE
y <- FALSE
result <- x & y
print(result)
# Output: FALSE

# Example 2:
vector1 <- c(TRUE, FALSE, TRUE)
vector2 <- c(TRUE, TRUE, FALSE)
result <- vector1 & vector2
print(result)
# Output: TRUE FALSE FALSE

OR Operator (|):
# Example 1:
x <- TRUE
y <- FALSE
result <- x | y
print(result)
# Output: TRUE

# Example 2:
vector1 <- c(TRUE, FALSE, TRUE)
vector2 <- c(TRUE, TRUE, FALSE)
result <- vector1 | vector2
print(result)
# Output: TRUE TRUE TRUE

NOT Operator (!):


# Example 1:
x <- TRUE
result <- !x
print(result)
# Output: FALSE

20
21311A05L9 Kalyan. K

# Example 2:
vector <- c(TRUE, FALSE, TRUE)
result <- !vector
print(result)
# Output: FALSE TRUE FALSE
Conditional Statements

Output: [1] "x is positive."

ii) Create four vectors namely patientid, age, diabetes, and status. Put these four
vectors into a data frame patient data and print the values using a for loop &
While loop

# Create the patientid vector


patientid <- c(1, 2, 3, 4, 5)
# Create the age vector
age <- c(25, 37, 52, 43, 29)

# Create the diabetes vector


diabetes <- c(FALSE, TRUE, TRUE, FALSE, TRUE)

# Create the status vector


status <- c("normal", "normal", "abnormal", "normal", "abnormal")
# Combine the vectors into a data frame
patientdata <- data.frame(patientid, age, diabetes, status)

21
21311A05L9 Kalyan. K

# Print the values using a for loop


cat("Printing using a for loop:\n")
for (i in 1: nrow(patientdata)) {
cat ("Patient ID:", patientdata[i, "patientid"],
"Age:", patientdata[i, "age"],
"Diabetes:", patientdata[i, "diabetes"],
"Status:", patientdata[i, "status"], "\n")
}
# Print the values using a while loop
cat("\nPrinting using a while loop:\n")
i <- 1
while (i <= nrow(patientdata)) {
cat("Patient ID:", patientdata[i, "patientid"],
"Age:", patientdata[i, "age"], "Diabetes:",
patientdata[i, "diabetes"], "Status:",
patientdata[i, "status"], "\n")
i <- i + 1
}

Output:

22
21311A05L9 Kalyan. K

iii. Create a user-defined function to compute the square of an integer in R

Output:

23
21311A05L9 Kalyan. K

iv. Recursion function for a) factorial of a number b) find nth Fibonacci number

# Define the factorial function


factorial <- function(n) { if
(n <= 1) {
return(1)
} else {
return(n * factorial(n-1))
}
}
# Define the Fibonacci function
fibonacci <- function(n) {
if (n <= 1) {
return(n)
} else {
return(fibonacci(n-1) + fibonacci(n-2))
}
}

# Test the functions with some values cat("The


factorial of 5 is", factorial(5), "\n") cat("The
factorial of 0 is", factorial(0), "\n")
cat("The 10th Fibonacci number is", fibonacci(10), "\n")
cat("The 20th Fibonacci number is", fibonacci(20), "\n")

Output:

24
21311A05L9 Kalyan. K

8. Write R code for

i) Illustrate Quick Sort

# Define the quick sort function


quick_sort <- function(arr) {
if (length(arr) <= 1) {
return(arr)
}
pivot <- arr[1]
left <- arr[-1][arr[-1] <= pivot]
right <- arr[-1][arr[-1] > pivot]
return(c(quick_sort(left), pivot, quick_sort(right)))
}

# Test the function with an example array


arr <- c(10, 5, 2, 8, 3, 9)
cat("Original array:", arr, "\n") cat("Sorted
array:", quick_sort(arr), "\n")

In this program, we define a function called quick_sort that takes an array arr as
an
argument and returns the sorted array. The function first checks if the length of the array is
less than or equal to 1, and if so, returns the array as is. Otherwise, it selects a pivot element
(in this case, the first element of the array), and partitions the array into two subarrays: one
containing elements less than or equal to the pivot, and another containing elements greater
than the pivot. It then recursively applies the quick sort algorithm to each subarray and
concatenates the sorted subarrays with the pivot element.
We then test the function with an example array arr and print the original and sorted
arrays using the cat() function.
Here's the output of the program:

25
21311A05L9 Kalyan. K

ii. Illustrate Binary Search Tree

i) # Define the BSTNode class


BSTNode <- setRefClass("BSTNode",
fields = list(
value = "numeric",
left = "BSTNode",
right = "BSTNode"
)
)
# Define the BST class
BST <- setRefClass("BST",
fields = list(
root = "BSTNode"
),
methods = list(
# Insert a new value into the BST
insert = function(value) {
node <- new (BSTNode, value=value)
if (is.null(root)) {
root <<- node
} else {
current <- root
while (TRUE) {
if (value < current$value) {
if (is.null(current$left)) {
current$left <<- node
break
} else {
current <- current$left
}
} else {
if (is.null(current$right)) {
current$right <<- node
break
} else {

26
21311A05L9 Kalyan. K

current <- current$right


}
}
}
}
},

# Search for a value in the BST


search = function(value) {

current <- root


while ( !is.null(current)) {
if (value == current$value) {
return (TRUE)
} else if (value < current$value) {
current <- current$left
} else {
current <- current$right
}
}
return(FALSE)
}
)
)
# Test the BST class
bst <- new(BST)
bst$insert(5)
bst$insert(3)
bst$insert(7)
bst$insert(1)
bst$insert(9)
cat("Searching for 1 in the BST:", bst$search(1), "\n")
cat("Searching for 8 in the BST:", bst$search(8), "\n")

27
21311A05L9 Kalyan. K

In this program, we define two classes: BSTNode and BST.


The BSTNode class represents a node in the BST and contains three
fields: value (the value of the node), left (a reference to the left child node), and
right (a reference to the right child node). We define this class using the
setRefClass() function from the methods package.
The BST class represents the BST data structure and contains one field: root
(a reference to the root node of the BST). We also define two methods for the BST
class: insert (which inserts a new value into the BST) and search (which searches
for a valuein the BST). The insert method works by traversing the BST and finding
the appropriate place to insert the new node, while the search method works by
traversing the BST and comparing the value with each node in the tree until the
value is found or the end of the tree is reached.
We then test the BST class by creating a new instance of the class (bst) and
inserting some values (5, 3, 7, 1, and 9) into the BST using the insert method. We
then search for the values 1 and 8 using the search method and print the results
using the cat() function.

28
21311A05L9 Kalyan. K

9. Write R command to
i) illustrate Mathematical functions & I/O functions

i) Mathematical functions:
# Example of mathematical functions in R
# Square root function
sqrt(16)
# Exponential function
exp(2)
# Natural logarithm function
log(10)
# Sine function (in radians)
sin(pi/2)
Output:
[1] 4
[1] 7.389056
[1] 2.302585
[1] 1

I/O functions:
# Example of I/O functions in R
# Read input from the user
name <- readline(prompt = "Enter your name: ")
cat("Hello, ", name, "!")
# Write output to a file
data <- c(1, 2, 3, 4, 5)
write(data, file = "output.txt")
# Read input from a file
input_data <- scan(file = "input.txt")
cat("The input data is: ", input_data, "\n")

Output:
Enter your name: John
Hello, John!
The input data is: 1 2 3 4 5

29
21311A05L9 Kalyan. K

In this example, we use the readline() function to read input from the user and the cat()
function to print output to the console. We also use the write() function to write output to a
file and the scan() function to read input from a file. Note that in this example, we assume
that there are two files named input.txt and output.txt in the current working directory.

ii. Illustrate Naming of functions and sapply(), lapply(), tapply() & mapply()

# Define a named function


add_two <- function(x) {
return(x + 2)
}
# Use the sapply() function to apply the function to a vector
vec <- c(1, 2, 3, 4)
sapply(vec, add_two)
# Use the lapply() function to apply the function to a list

lst <- list(a = 1, b = 2, c = 3)


lapply(lst, add_two)
# Use the tapply() function to apply the function to subsets of a vector
vec <- c(1, 2, 3, 4)
group <- c("A", "B", "A", "B")
tapply(vec, group, add_two)
# Use the mapply() function to apply the function to multiple vectors
vec1 <- c(1, 2, 3, 4)
vec2 <- c(2, 3, 4, 5)
mapply(add_two, vec1, vec2)

30
21311A05L9 Kalyan. K

Output:
[1] 3 4 5 6
$a
[1] 3
$b
[1] 4
$c
[1] 5
$A
[1] 3 5
$B
[1] 4 6
[1] 3 5 5 7
In this example, we define a named function add_two() that adds 2 to its input. We
then use the sapply() function to apply the function to a vector, the lapply() function to apply
the function to a list, the tapply() function to apply the function to subsets of a vector based
on a grouping variable, and the mapply() function to apply the function to multiple vectors.
Note that the sapply() function simplifies the output to a vector, while the lapply() function
preserves the output as a list. The tapply() function applies the function to subsets of the
input vector based on a grouping variable, and the mapply() function applies the function to
multiple vectors element- wise.

31
21311A05L9 Kalyan. K

10. Write R command for

i) Pie chart & 3D Pie Chart, Bar Chart to demonstrate the percentage conveyance
of various ways for traveling to office such as walking, car, bus, cycle, and train

# Create a data frame with conveyance and percentage columns


conveyance <- c("Walking", "Car", "Bus", "Cycle", "Train")
percentage <- c(20, 30, 25, 10, 15)
df <- data.frame(conveyance, percentage)
# Create a pie chart
pie(df$percentage, labels = df$conveyance, main = "Conveyance to Office")

# Create a 3D pie chart


library(plotrix)
pie3D(df$percentage, labels = df$conveyance, main = "Conveyance to Office")

# Create a bar chart


barplot(df$percentage, names.arg = df$conveyance, main = "Conveyance to Office")

In this example, we first create a data frame with two columns: conveyance and
percentage, which store the conveyance modes and their corresponding percentages. We
then create a pie chart using the pie() function, a 3D pie chart using the pie3D() function
from the plotrix package, and a bar chart using the barplot() function. All three charts
display the same data, but provide different visual representations of the conveyance
percentages.

ii) Using a chart legend, show the percentage conveyance of various ways for
traveling to office such as walking, car, bus, cycle, and train.
(a) Walking is assigned red color, car – blue color, bus – yellow color, cycle –
green color, and train – white color; all these values are assigned through
cols and lbls variables and the legend function.
(b) The fill parameter is used to assign colors to the legend.
(c) Legend is added to the top-right side of the chart, by assigning

# Create a data frame with conveyance and percentage columns


conveyance <- c("Walking", "Car", "Bus", "Cycle", "Train")
percentage <- c(20, 30, 25, 10, 15)

32
21311A05L9 Kalyan. K

df <- data.frame(conveyance, percentage)

# Create a bar chart and assign colors to each conveyance mode


cols <- c("red", "blue", "yellow", "green", "white")
names(cols) <- df$conveyance
barplot(df$percentage, col = cols, main = "Conveyance to Office")

# Create a legend for the chart


lbls <- c("Walking", "Car", "Bus", "Cycle", "Train")
legend("topright", legend = lbls, fill = cols)

In this example, we first create a data frame with two columns: conveyance and
percentage, which store the conveyance modes and their corresponding percentages. We
then create a bar chart using the barplot() function and assign colors to each conveyance
mode using a vector cols. We assign the conveyance modes to the colors using the names()
function.

Next, we create a legend for the chart using the legend() function. We specify the
location of the legend using the "topright" argument, and provide the legend labels and
colors using the legend and fill arguments, respectively. The colors in the legend match
the colors used in the bar chart.
Overall, this program creates a bar chart with a legend that shows the percentage
conveyance of various ways for traveling to office, and assigns different colors to each
conveyance mode. Using box plots, Histogram, Line Graph, Multiple line graphs and
scatter plot to demonstrate the relation between the cars speed and the distance taken to stop,
Consider the parameters data and x Display the speed and dist parameter of Cars data set
using x and data parameters

iii. Using box plots, Histogram, Line Graph, Multiple line graphs and scatter plot to
demonstrate the relation between the cars speed and the distance taken to stop,
Consider the parameters data and x Display the speed and dist parameter of
Cars data set using x and data parameters

33
21311A05L9 Kalyan. K

# Load the cars dataset


data(cars)

# Display the speed and dist parameters using x and data parameters
x <- cars$speed
data <- cars$dist

# Create a box plot of the data


boxplot(data, main = "Box Plot of Distance to Stop")

# Create a histogram of the data


hist(data, main = "Histogram of Distance to Stop")

# Create a line graph of the data


plot(x, data, type = "l", main = "Line Graph of Distance to Stop vs. Speed", xlab = "Speed",
ylab = "Distance")

# Create multiple line graphs of the data


par(mfrow = c(2, 2))
plot(x, data, type = "l", main = "Line Graph 1")
plot(data, x, type = "l", main = "Line Graph 2")
plot(x, data^2, type = "l", main = "Line Graph 3")
plot(x, data^3, type = "l", main = "Line Graph 4")

# Create a scatter plot of the data


plot(x, data, main = "Scatter Plot of Distance to Stop vs. Speed", xlab = "Speed", ylab =
"Distance")

In this program, we first load the cars dataset using the data() function. We then
assign the speed and dist parameters to variables x and data, respectively.
We then use various plotting functions to demonstrate the relationship between the
car's speed and the distance taken to stop. The boxplot() function is used to create a box plot
of the data, while the hist() function is used to create a histogram.
We also use the plot() function to create a line graph of the data, and the par()
function to create multiple line graphs in a 2x2 grid. Finally, we use the plot() function to
create a scatter plot of the data. Overall, this program provides a range of visualization options
for exploring the relationship between the car's speed and the distance taken to stop.

34

You might also like