0% found this document useful (0 votes)
23 views16 pages

Acl 7-9 in R

The document contains exercises focused on creating and manipulating lists and factors in R, including adding/removing elements and modifying factors. It also covers loops and functions, demonstrating how to calculate sums, reverse strings, generate Fibonacci series, check for prime numbers, and create multiplication tables. Additionally, it includes analysis of datasets like Iris and mtcars, showcasing data visualization techniques such as box plots and scatter plots.

Uploaded by

radiveg204
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)
23 views16 pages

Acl 7-9 in R

The document contains exercises focused on creating and manipulating lists and factors in R, including adding/removing elements and modifying factors. It also covers loops and functions, demonstrating how to calculate sums, reverse strings, generate Fibonacci series, check for prime numbers, and create multiplication tables. Additionally, it includes analysis of datasets like Iris and mtcars, showcasing data visualization techniques such as box plots and scatter plots.

Uploaded by

radiveg204
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

EXERCISE NO:7

LIST AND FACTORS


DATE:

7A) Creating and Accessing Elements in a List

Aim:
To create a list and access its elements in R.

Algorithm:
Step 1: Create a list with multiple elements.
Step 2: Access and print the elements of the list.

Program:
my_list <- list(name = "John", age = 30, city = "New York")
print("List Elements:")
print(my_list$name) # accessing the "name" element
print(my_list$age) # accessing the "age" element
print(my_list$city) # accessing the "city" element

Output:
[1] "List Elements:"
[1] "John"
[1] 30
[1] "New York"

Result:-

Thus, the program has been executed successfully


12
7B) Creating and Modifying Factors

Aim:
To create and modify factors in R.

Algorithm:
Step 1: Create a vector of categorical data.
Step 2: Convert the vector into a factor.
Step 3: Modify the levels of the factor.
Step 4: Print the modified factor.

Program:
category <- c("A", "B", "A", "C", "B", "B")
category_factor <- factor(category)
levels(category_factor) <- c("Group A", "Group B", "Group C")
print("Modified Factor:")
print(category_factor)

Output:
[1] "Modified Factor:"
[1] Group A Group B Group A Group C Group B Group B
Levels: Group A Group B Group C

Result:-

Thus, the program has been executed successfully


13
7C) Adding and Removing Elements from a List

Aim:
To add and remove elements from a list in R.

Algorithm:
Step 1: Create an empty list.
Step 2: Add elements to the list using the $ operator or the [[ indexing.
Step 3: Remove an element from the list using the [[ indexing and assignment.
Step 4: Print the modified list.

Program:
my_list <- list()
my_list$name <- "John"
my_list$age <- 30
my_list$name <- NULL
print("Modified List:")
print(my_list)

Output:
[1] "Modified List:"
$age
[1] 30

Result:-

Thus, the program has been executed successfully


14
7D) Working with Factors and Levels

Aim:
To work with factors and levels in R.

Algorithm:
Step 1: Create a vector of categorical data.
Step 2: Convert the vector into a factor.
Step 3:Print the levels of the factor.
Step 4:Reorder the levels of the factor.
Step 5: Print the modified levels.

Program:
category <- c("A", "B", "A", "C", "B", "B")
category_factor <- factor(category)
print("Original Levels:")
print(levels(category_factor))
category_factor <- factor(category_factor, levels = c("B", "A", "C"))
print("Modified Levels:")
print(levels(category_factor))

Output:
[1] "Original Levels:"
[1] "A" "B" "C"
[1] "Modified Levels:"
[1] "B" "A" "C"

Result:-

Thus, the program has been executed successfully


15
EXERCISE NO: 8
LOOPS AND FUNCTIONS
DATE:

8A) Sum of Even Numbers


Aim:
To calculate the sum of even numbers from 1 to a given number.

Algorithm:
Step 1: Define a function named ‘sum_even_numbers’ that takes a parameter n.
Step 2: Initialize a variable result to 0.
Step 3: Use a for loop to iterate from 1 to n.
Step 4: Check if the current number i is divisible by 2 using the modulo operator
(%%).
Step 5: If i is even, add it to the result.
Step 6: Return the final value of result.
Step 7: In the main program, set the value of number to the desired number up to
which you want to calculate the sum of even numbers.
Step 8: Call the ‘sum_even_numbers’ function with number as the argument and store
the result in ‘sum_result’.
Step 9: Print the result using the print function, which displays the sum of even
numbers.

Program:
sum_even_numbers <- function(n)
{result <- 0
for (i in 1:n) {
if (i %% 2 == 0) {
result <- result + i
}
}
return(result)
}
number <- 10
sum_result <- sum_even_numbers(number)
print(paste("The sum of even numbers from 1 to", number, "is", sum_result))
Output:
[1] "The sum of even numbers from 1 to 10 is 30"

Thus, the program has been executed successfully


16
Result:

Thus, the program has been executed successfully


17
8B) Reverse a String

Aim:
To reverse a given string using R Program
Algorithm:

1. Define a function named ‘reverse_string’ that takes a parameter string.


2. Initialize an empty string variable reversed.
3. Use a for loop to iterate from the length of the string (nchar(string)) to 1.
4. Extract each character from the original string starting from the last character
using the ‘substr’ function and concatenate it to the reversed string.
5. Return the final reversed string.
6. In the main program, set the value of text to the desired string to be reversed.
7. Call the ‘reverse_string’ function with text as the argument and store the result in
‘reversed_text’.
8. Print the result using the print function, which displays the reversed string.

Program:
reverse_string <- function(string)
{reversed <- ""
for (i in nchar(string):1) {
reversed <- paste(reversed, substr(string, i, i), sep = "")
}
return(reversed)
}
text <- "Hello, World!"
reversed_text <- reverse_string(text)
print(paste("The reversed string is:", reversed_text))

Output:
[1] "The reversed string is: !dlroW ,olleH"

Result:

Thus, the program has been executed successfully


18
8C) Fibonacci Series
Aim:
To generate the Fibonacci series up to a given number of terms.
Algorithm:
Step 1: Define a function named fibonacci_series that takes a parameter n.
Step 2: Initialize a vector series with the first two numbers of the Fibonacci series,
i.e.,0 and 1.
Step 3: Check if n is less than or equal to 2.
Step 4: If n is less than or equal to 2, return the sliced portion of the series vector up to
n terms.
Step 5: If n is greater than 2, use a for loop to iterate from 3 to n.
Step 6: In each iteration, calculate the next Fibonacci number by adding the previous
two numbers and append it to the series vector.
Step 7: Return the final series vector.
Step 8: In the main program, set the value of terms to the desired number of terms in
the Fibonacci series.
Step 9: Call the fibonacci_series function with terms as the argument and store the
result in fib_series.
Step 10: Print the result using the print function, which displays the Fibonacci series.

Program:
fibonacci_series <- function(n)
{series <- c(0, 1)
if (n <= 2)
{ return(series[1:n]
)
} else {
for (i in 3:n) {
series <- c(series, series[i-1] + series[i-2])
}
return(series)
}
}
19
terms <- 10
fib_series <- fibonacci_series(terms)

print(paste("The Fibonacci series up to", terms, "terms is:", paste(fib_series, collapse


=", ")))

Output:
[1] "The Fibonacci series up to 10 terms is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 3

Result:

Thus, the program has been executed successfully

20
8D) Check Prime Number
Aim:

To check if a given number is prime or not.

Algorithm:

Step 1: Define a function named is_prime that takes a parameter n


Step 2: Check if n is less than or equal to 1. If true, return FALSE because prime
numbers start from 2.
Step 3: Use a for loop to iterate from 2 to the square root of n
Step 4: Check if n is divisible by the loop variable i using the modulo operator
(%%).
Step 5: If n is divisible by i, return FALSE because it is not a prime number
Step 6:If the loop completes without finding a divisor for n, return TRUE because
it is a prime number.
Step 7: In the main program, set the value of number to the desired number to be
checked for primality.
Step 8: Call the is_prime function with number as the argument.
Step 9: Use an if-else statement to check the returned value and print the
corresponding message.
Program:
is_prime <- function(n)

{if (n <= 1)

{ return(FALSE)

for (i in 2:sqrt(n))

{if (n %% i == 0)

{return(FALSE)

return(TRUE)
21
}

number <- 17

if (is_prime(number)) {

print(paste(number, "is a prime number."))

} else {

print(paste(number, "is not a prime number."))

Output:

[1] "17 is a prime number."

Result:

Thus, the program has been executed successfully


22
8E) Multiplication Table
Aim:
To generate the multiplication table for a given number.
Algorithm:
Step 1: Define a function named multiplication_table that takes a parameter n.
Step 2: Use a for loop to iterate from 1 to 10.
Step 3: Calculate the result of multiplying n with the loop variable i and store it in
the result variable.
Step 4: Print the multiplication expression and the result using the print function.
Step 5: In the main program, set the value of number to the desired number for
which you want to generate the multiplication table.
Step 6: Print a message indicating the multiplication table for the number.
Call the multiplication_table function with number as the argument.
Program:

multiplication_table <- function(n)

{for (i in 1:10) {

result <- n * i

print(paste(n, "x", i, "=", result))

number <- 5

print(paste("Multiplication table for", number, ":"))

multiplication_table(number)

Output:

[1] "Multiplication table for 5 :"

[1] "5 x 1 = 5"

[1] "5 x 2 = 10"

[1] "5 x 3 = 15"


23
[1] "5 x 4 = 20"

[1] "5 x 5 = 25"

[1] "5 x 6 = 30"

[1] "5 x 7 = 35"

[1] "5 x 8 = 40"

[1] "5 x 9 = 45"

[1] "5 x 10 = 50"

Result:

Thus, the program has been executed successfully

24
EXERCISE NO: 9

DATE: PLOTS AND TABULATIONS

9A) Analyzing the Iris Dataset

Aim:

To perform basic analysis on the Iris dataset.

Algorithm:

Step 1: Load the Iris dataset using the iris function.

Step 2: View the structure of the dataset using the str() function.

Step 3: Calculate summary statistics using the summary() function.

Step 4: Create a box plot to visualize the distribution of the Sepal Length variable.

Step 5: Create a scatter plot to visualize the relationship between Petal Length and Petal

Width.

Program:

data(iris) # Load the Iris dataset

str(iris)

summary(iris)

boxplot(Sepal.Length ~ Species, data = iris, main = "Box Plot - Sepal Length",

xlab = "Species", ylab = "Sepal Length")

plot(Petal.Length ~ Petal.Width, data = iris, main = "Scatter Plot - Petal Length vs.

Petal Width", xlab = "Petal Width", ylab = "Petal Length")

Output:
Sepal.Length Sepal.Width Petal.Length Petal.Width
Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100
1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300
Median :5.800 Median :3.000 Median :4.350 Median :1.300
Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199

25
3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800
Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500
Species
setosa :50
versicolor:50
virginica :50

Result:

Thus, the program has been executed successfully

26
9B) Analyzing the mtcars Dataset

Aim:

To perform analysis on the mtcars dataset.

Algorithm:

Step 1: Load the mtcars dataset using the mtcars function.

Step 2: View the structure of the dataset using the str() function.

Step 3: Calculate summary statistics using the summary() function.

Step 4: Create a histogram to visualize the distribution of MPG (Miles per Gallon).

Step 5: Create a scatter plot to visualize the relationship between Horsepower and MPG.

Program:

data(mtcars)
str(mtcars)
summary(mtcars)
hist(mtcars$mpg, main = "Histogram - MPG", xlab = "MPG", ylab = "Frequency",
col = "lightblue")
plot(mpg ~ hp, data = mtcars, main = "Scatter Plot - Horsepower vs. MPG", xlab =
"Horsepower", ylab = "MPG")
Output:

mpg cyl disp hp drat


Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0 Min. :2.760
1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5 1st Qu.:3.080
Median :19.20 Median :6.000 Median :196.3 Median :123.0 Median :3.695
Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7 Mean :3.597 3rd
Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0 3rd Qu.:3.920 Max.
:33.90 Max. :8.000 Max. :472.0 Max. :335.0 Max. :4.930
wt qsec vs am gear
Min.:1.513 Min.:14.50 Min.:0.0000 Min.:0.0000 Min.:3.000
1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000 1st Qu.:0.0000 1st Qu.:3.000
Median :3.325 Median :17.71 Median :0.0000 Median :0.0000 Median :4.000
Mean :3.217 Mean :17.85 Mean :0.4375 Mean :0.4062 Mean :3.688 3rd
Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000 3rd Qu.:1.0000 3rd Qu.:4.000 Max.
:5.424 Max. :22.90 Max. :1.0000 Max. :1.0000 Max. :5.000
carb
Min. :1.000
1st Qu.:2.000
Median :2.000
Mean :2.812
3rd Qu.:4.000
Max. :8.000

27

You might also like