0% found this document useful (0 votes)
4 views38 pages

R Programming Lab Exercises Guide

Uploaded by

ssascw.bca
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)
4 views38 pages

R Programming Lab Exercises Guide

Uploaded by

ssascw.bca
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

lOMoARcPSD|27644403

LAB - EWEWE

History (MIT School of Distance Education)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by ranju mani (ranjunpt@[Link])
lOMoARcPSD|27644403

EX NO:1

Program To Convert the given temperature from Fahrenheit to Celsius


and vice versa depending Upon user‘s choice.

# Convert Celsius to Fahrenheit


celsius_to_fahrenheit <- function(celsius)
{ return((celsius * 9/5) + 32)
}

# Example: Convert 25 degrees Celsius to Fahrenheit


celsius_temp <- 25
fahrenheit_temp <- celsius_to_fahrenheit(celsius_temp)
cat(celsius_temp, "degrees Celsius is equal to", fahrenheit_temp, "Fahrenheit\n")

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

Output:

25 degrees Celsius is equal to 77 Fahrenheit

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

# Convert Fahrenheit to Celsius


fahrenheit_to_celsius <- function(fahrenheit)
{ return((fahrenheit - 32) * 5/9)
}

# Example: Convert 77 degrees Fahrenheit to Celsius


fahrenheit_temp <- 77
celsius_temp <- fahrenheit_to_celsius(fahrenheit_temp)
cat(fahrenheit_temp, "degrees Fahrenheit is equal to", celsius_temp, "Celsius\n")

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

Output:

77 degrees Fahrenheit is equal to 25 Celsius

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

EX NO:2

Program, to find the area of rectangle, square, circle and triangle by accepting
suitable input parameters from user.

# Function to calculate the area of a rectangle


calculate_rectangle_area <- function() {
length <- [Link](readline(prompt = "Enter the length of the rectangle: "))
width <- [Link](readline(prompt = "Enter the width of the rectangle: "))
area <- length * width
cat("Area of the rectangle:", area, "\n")
}

# Function to calculate the area of a square


calculate_square_area <- function() {
side <- [Link](readline(prompt = "Enter the side length of the square: "))
area <- side * side
cat("Area of the square:", area, "\n")
}

# Function to calculate the area of a circle


calculate_circle_area <- function() {
radius <- [Link](readline(prompt = "Enter the radius of the circle: "))
area <- pi * radius^2
cat("Area of the circle:", area, "\n")
}

# Function to calculate the area of a triangle


calculate_triangle_area <- function() {
base <- [Link](readline(prompt = "Enter the base of the triangle: "))
height <- [Link](readline(prompt = "Enter the height of the triangle: "))
area <- 0.5 * base * height
cat("Area of the triangle:", area, "\n")
}

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

# Main program loop


while (TRUE) {
cat("\nSelect a shape to calculate its area:\n")
cat("1. Rectangle\n")
cat("2. Square\n")
cat("3. Circle\n")
cat("4. Triangle\n")
cat("5. Exit\n")

choice <- [Link](readline(prompt = "Enter your choice (1-5): "))

if (choice == 1) {
calculate_rectangle_area()
} else if (choice == 2) {
calculate_square_area()
} else if (choice == 3) {
calculate_circle_area()
} else if (choice == 4) {
calculate_triangle_area()
} else if (choice == 5) {
cat("Exiting program.\n")
break
} else {
cat("Invalid choice. Please enter a number between 1 and 5.\n")
}
}

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

Output

Select a shape to calculate its area:


1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 2
Enter the side length of the square: 5
Area of the square: 25

Select a shape to calculate its area:


1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 1
Enter the length of the rectangle:
3 Enter the width of the rectangle:
4 Area of the rectangle: 12

Select a shape to calculate its area:


1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 3
Enter the radius of the circle: 5
Area of the circle: 78.53982

Select a shape to calculate its area:


1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

Enter your choice (1-5): 4


Enter the base of the triangle:
2
Enter the height of the triangle: 3
Area of the triangle: 3

Select a shape to calculate its area:


1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 5
Exiting program.
>

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

EX NO: 3

Write a program to find list of even numbers from1to n using


R- Loops.

find_even_numbers <- function(n) {


# Initialize an empty vector to store even numbers even_numbers <- c()

# Loop from 1 to n for (i in


1:n) {
# Check if the current number is even if (i %% 2 ==
0) {
# Add the even number to the vector even_numbers <-
c(even_numbers, i)
}
}

# Return the list of even numbers


return(even_numbers)
}

# Example usage:
n_value <- 10
result <- find_even_numbers(n_value) print(result)

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

OUTPUT

[1] 2 4 6 8 10 12 14 16 18

10

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

EX NO: 4

Create a function to print squares of numbers in sequence

print_squares_in_sequence <- function(n) {


# Generate a sequence of numbers from 1 to n numbers <- 1:n

# Calculate the squares of these numbers squares <- numbers^2

# Print each number and its square in a formatted way for (i in


1:length(numbers)) {
cat(numbers[i], "^2 = ", squares[i], "\n")
}
}
print_squares_in_sequence(5)

11

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

OUTPUT

1 ^2 = 1
2 ^2 = 4
3 ^2 = 9
4 ^2 = 16
5 ^2 = 25

12

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

EX NO:5

Write a program to join columns and rows in a data frame using cbind() and
rbind() in R.

a. cbind()

# Create the first data frame df1 <-


[Link](
Name = c("Alice", "Bob"), Age = c(25,
30)
)

# Create the second data frame df2 <-


[Link](
Height = c(160, 175), Weight =
c(55, 70)
)

# Combine the data frames by columns


combined_df_cols <- cbind(df1, df2)

# Print the combined data frame


print(combined_df_cols)

13

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

OUTPUT

Name Age Height Weight

1 Alice 25 160 55

2 Bob 30 175 70

14

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

b. rbind()

# Create the first data frame df3 <-


[Link](
Name = c("Charlie", "David"), Score =
c(90, 85)
)

# Create the second data frame df4 <-


[Link](
Name = c("Eve", "Frank"), Score =
c(92, 88)
)

# Combine the data frames by rows combined_df_rows


<- rbind(df3, df4)

# Print the combined data frame


print(combined_df_rows)

15

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

OUTPUT

Name Score

1 Charlie 90

2 David 85

3 Eve 92

4 Frank 88

16

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

EX NO:6

Implement different String Manipulation functions in R.

# Define a sample string


my_string <- "R Programming is FUN!"

# 1. nchar(): Get the number of characters in a string


cat("Number of characters:", nchar(my_string), "\n")

# 2. toupper(): Convert to uppercase


cat("Uppercase:", toupper(my_string), "\n")

# 3. tolower(): Convert to lowercase


cat("Lowercase:", tolower(my_string), "\n")

# 4. substr(): Extract a substring


cat("Substring (chars 3 to 10):", substr(my_string, 3, 10), "\n")

# 5. paste(): Concatenate strings


string1 <- "Hello"
string2 <- "World"
cat("Concatenated string:", paste(string1, string2), "\n")
cat("Concatenated with separator:", paste(string1, string2, sep = "-"), "\
n")

# 6. strsplit(): Split a string by a delimiter


split_string <- strsplit(my_string, " ")
cat("Split string:", unlist(split_string), "\n") # unlist to view as a vector

# 7. sub(): Replace the first occurrence of a pattern


modified_string_sub <- sub("Programming", "Coding", my_string)
cat("After sub():", modified_string_sub, "\n")

# 8. gsub(): Replace all occurrences of a pattern


another_string <- "Apple pie, apple juice, apple sauce"
modified_string_gsub <- gsub("apple", "orange", another_string)
cat("After gsub():", modified_string_gsub, "\n")

17

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

# 9. grep(): Find matching patterns


matching_indices <- grep("is", my_string)
cat("Indices where 'is' is found:", matching_indices, "\n") # Returns 1 if found in the string

# 10. grepl(): Check if a pattern exists (returns logical)


contains_fun <- grepl("FUN", my_string)
cat("Does the string contain 'FUN'?", contains_fun, "\n")

18

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

output

Number of characters: 21
Uppercase: R PROGRAMMING IS FUN!
Lowercase: r programming is fun!
Substring (chars 3 to 10): Programm
Concatenated string: Hello World
Concatenated with separator: Hello-World
Split string: R Programming is FUN!
After sub(): R Coding is FUN!
After gsub(): Apple pie, orange juice, orange sauce
Indices where 'is' is found: 1
Does the string contain 'FUN'? TRUE

19

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

EX NO:6

Implement different data structures in R(Vectors, Lists, Data Frames)

Vectors
# Numeric vector
numeric_vector <- c(1, 5, 9, 13)
print(numeric_vector)

# Character vector
character_vector <- c("apple", "banana", "cherry")
print(character_vector)

# Logical vector
logical_vector <- c(TRUE, FALSE, TRUE)
print(logical_vector)

20

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

output

[1] 1 5 9 13
[1] "apple" "banana" "cherry"
[1] TRUE FALSE TRUE

21

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

Lists
# Creating a list with different data types
my_list <- list(
name = "Alice",
age = 30,
scores = c(85, 92, 78),
is_student = TRUE
)
print(my_list)

# Accessing elements of a list


print(my_list$name)
print(my_list[[3]][2]) # Accessing the second element of the 'scores' vector

22

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

output

$name

[1] "Alice"

$age
[1] 30

$scores
[1] 85 92 78

$is_student
[1] TRUE

[1] "Alice"
[1] 92

23

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

Data Frames

# Creating a data frame


employee_data <-
[Link]( ID = c(101, 102,
103),
Name = c("John Doe", "Jane Smith", "Peter Jones"),
Department = c("HR", "IT", "Finance"),
Salary = c(60000, 75000, 62000)
)
print(employee_data)

# Accessing columns of a data frame


print(employee_data$Name)
print(employee_data[, "Department"])

# Accessing rows of a data frame


print(employee_data[2, ]) # Second row
print(employee_data[employee_data$Salary > 70000, ]) # Rows where salary is greater than
70000

24

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

output

ID Name Department Salary


1 101 John Doe HR 60000
2 102 Jane Smith IT 75000
3 103 Peter Jones Finance 62000

[1] "John Doe" "Jane Smith" "Peter Jones"


[2] [1] "HR" "IT" "Finance"

ID Name Department
Salary 2 102 Jane SmithIT
75000
ID Name Department
Salary 2 102 Jane SmithIT75000

25

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

EX NO:8

Write a program to read a csv file and analyze the data in the file in R.
1. Prepare your CSV file:
Ensure you have a CSV file available. For this example, assume a file named [Link]
in your working directory with the following content: Code
Name,Age,City,Score
Alice,25,New York,85
Bob,30,London,92
Charlie,22,Paris,78
David,28,Berlin,95
Eve,26,Tokyo,88
2. R Program:
Code
# Set your working directory (optional, but good practice if the file isn't in your default
directory)
# setwd("C:/Users/YourUsername/Desktop") # Replace with your actual path

# 1. Read the CSV file into a data frame


# stringsAsFactors = FALSE prevents character columns from being converted to factors
automatically
data <- [Link]("[Link]", stringsAsFactors = FALSE)

# 2. Inspect the data


# Display the first few rows print("First few
rows of the data:") head(data)

# Get the structure of the data frame (data types of columns) print("\nStructure of the data:")
str(data)

# Get summary statistics for numerical columns print("\


nSummary statistics of the data:") summary(data)

# Get the dimensions (number of rows and columns) print("\


nDimensions of the data (rows, columns):") dim(data)

# 3. Perform basic data analysis


# Calculate the mean of a numerical column (e.g., Score) mean_score <-
mean(data$Score)
print(paste("\nMean Score:", mean_score))

# Find the maximum value in a numerical column (e.g., Age) max_age <-
max(data$Age)
print(paste("Maximum Age:", max_age))

# Filter data based on a condition (e.g., people with Score > 90) high_scorers <-
subset(data, Score > 90)

26

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

print("\nIndividuals with a score greater than 90:") print(high_scorers)


# Count the occurrences of unique values in a categorical column (e.g., City) city_counts <-
table(data$City)
print("\nCount of individuals by City:")
print(city_counts)

27

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

Output

head(data)
Name Age City Score
1 Alice 25 New York 85
2 Bob 30 London 92
3 Charlie 22 Paris 78
4 David 28 Berlin 95
5 Eve 26 Tokyo 88

str(data)
'[Link]': 5 obs. of 4 variables:
$ Name : chr "Alice" "Bob" "Charlie" "David" ...
$ Age : int 25 30 22 28 26
$ City : chr "New York" "London" "Paris" "Berlin" ...
$ Score: int 85 92 78 95 88

summary(data)
Name Age City Score
Length:5 Min. :22.0 Length:5 Min. :78.0
Class :character 1st Qu.:25.0 Class :character 1st Qu.:85.0
Mode :character Median :26.0 Mode :character Median :88.0
Mean :26.2 Mean :87.6
3rd Qu.:28.0 3rd Qu.:92.0
Max. :30.0 Max. :95.0

dim(data)
[1] 5 4

print(paste("\nMean Score:", mean_score))


[1] "\nMean Score: 87.6"

print(paste("Maximum Age:", max_age))

[1] "Maximum Age: 30"


>

28

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

"\nIndividuals with a score greater than 90:"


> print(high_scorers)
Name Age City Score
2 Bob 30 London 92
4 David 28 Berlin 95

print("\nCount of individuals by City:")


[1] "\nCount of individuals by City:"
> print(city_counts)

Berlin London New York Paris Tokyo


1 1 1 1 1

29

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

EX NO:9

Create pie chart and bar chart using R.

[Link]

A <- c(17, 2, 8, 13, 1, 22)


B <- c("Jan", "feb", "Mar", "Apr", "May", "Jun")

barplot(A, [Link] = B, xlab ="Month",


ylab ="Articles", col ="green",
main ="GeeksforGeeks-Article chart")

30

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

31

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

[Link]

expenditure <- c(600, 300, 150, 100, 200)

result <- pie(expenditure,


main = "Monthly Expenditure Breakdown",
labels = c("Housing", "Food", "Cloths", "Entertainment", "Other")
)

print(result)

32

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

33

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

EX NO:10

Program to find factorial of the given number using recursive function

rec_fac <- function(x)


{
if(x==0 || x==1)
{
return(1)
}
else
{
return(x*rec_fac(x-1))
}
}

rec_fac(3)

34

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

output

[1] 6

35

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

EX NO:11

Write a R program to count the number of even and odd numbers from array of N
numbers

# Function to count even and odd numbers in a vector


count_even_odd <- function(numbers) {
even_count <- 0
odd_count <- 0

for (num in numbers) {


if (num %% 2 == 0)
{
even_count <- even_count + 1
} else {
odd_count <- odd_count + 1
}
}

return(list(even = even_count, odd = odd_count))


}

# Example usage:
# Create a sample array (vector in R) of numbers
my_numbers <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)

# Call the function to count even and odd numbers


counts <- count_even_odd(my_numbers)

# Print the results


cat("Number of even numbers:", counts$even, "\n")
cat("Number of odd numbers:", counts$odd, "\n")

output
36

Downloaded by ranju mani (ranjunpt@[Link])


lOMoARcPSD|27644403

Number of even numbers: 7


Number of odd numbers: 8

37

Downloaded by ranju mani (ranjunpt@[Link])

You might also like