0% found this document useful (0 votes)
2 views27 pages

Full R Laboratory

The document is a laboratory record for students at Arunachala Arts and Science College, detailing various R programming exercises. It includes tasks such as temperature conversion, area calculations, and data structure implementations, along with the procedures and sample code for each exercise. The document serves as a guide for students to complete their laboratory work and prepare for university examinations.

Uploaded by

berlinrosej93
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)
2 views27 pages

Full R Laboratory

The document is a laboratory record for students at Arunachala Arts and Science College, detailing various R programming exercises. It includes tasks such as temperature conversion, area calculations, and data structure implementations, along with the procedures and sample code for each exercise. The document serves as a guide for students to complete their laboratory work and prepare for university examinations.

Uploaded by

berlinrosej93
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

ARUNACHALA

ARTS AND SCIENCE (WOMEN) COLLEGE


Vellichanthai – 629203, Kanyakumari District

Department of ________________________________________
LABORATORY RECORD
20 - 20

This is to certify that this is a bonafide record of the work done by

Ms.__________________________________________________ Register Number

_________________________ in the Laboratory during the ___________ Semester.

Staff-in-Charge Head of the Department

Submitted for the University Examination held on_____________________

Internal Examiner External Examiner


INDEX
Sl. Title Page Signature
No No.
1 Convert the given temperature from Fahrenheit to Celsius and vice
versa depending upon user’s choice.

2 Find the area of rectangle, square, circle and triangle by accepting


suitable input parameters from user.

3 Write a program to find list of even numbers from 1 to n using R-


Loops.
4 Create a function to print squares of numbers in sequence.

5 Join columns and rows in a data frame using cbind() and rbind()

6 Implement different String Manipulation functions

7 Implement different data structures (Vectors, Lists, Data Frames)

8 Write a program to read a csv file and analyze the data in the file

9 Create pie chart and bar chart for a data set

10 Create a data set and do statistical analysis on the data

11 Program to find factorial of the given number using recursive


function

12 Count the number of even and odd numbers from array of N


numbers.
[Link] :1 Convert the given temperature from Fahrenheit to Celsius and vice versa
Date : depending upon user’s choice

Aim
To write an R program that converts a given temperature from Fahrenheit to Celsius or from
Celsius to Fahrenheit based on the user’s choice.
Procedure:
1. Start the R program.
2. Create a function to convert Fahrenheit to Celsius.
3. Create another function to convert Celsius to Fahrenheit.
4. Display a menu asking the user to choose the type of conversion.
5. Read the user's choice (1 or 2).
6. If choice is 1, ask for Fahrenheit value and convert it too Celsius.
7. If choice is 2, ask for Celsius value and convert it to Fahrenheit.
8. Display the converted temperature.
9. If the user enters any wrong option, show an error message.
10. Stop the program.
Program
# 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")
# Convert Celsius to Fahrenheit
celsius_to_fahrenheit <- function(celsius) {
return((celsius * 9/5) + 32)
}
# Example: Convert 25 degrees Celsius to Fahrenheit
1
celsius_temp <- 25
fahrenheit_temp <- celsius_to_fahrenheit(celsius_temp)
cat(celsius_temp, "degrees Celsius is equal to", fahrenheit_temp, "Fahrenheit\n")
# Temperature Conversion Program in R
# Function to convert Fahrenheit to Celsius
fahrenheit_to_celsius <- function(fahrenheit) {
celsius <- (fahrenheit - 32) * 5/9
return(celsius)
}
# Function to convert Celsius to Fahrenheit
celsius_to_fahrenheit <- function(celsius) {
fahrenheit <- (celsius * 9/5) + 32
return(fahrenheit)
}
# Ask user for conversion type
cat("Temperature Conversion Program\n")
cat("1: Fahrenheit to Celsius\n")
cat("2: Celsius to Fahrenheit\n")
choice <- [Link](readline(prompt = "Enter your choice (1 or 2): "))
if (choice == 1) {
fahrenheit <- [Link](readline(prompt = "Enter temperature in Fahrenheit: "))
celsius <- fahrenheit_to_celsius(fahrenheit)
cat(fahrenheit, "°F is equal to", round(celsius, 2), "°C\n")
} else if (choice == 2) {
celsius <- [Link](readline(prompt = "Enter temperature in Celsius: "))
fahrenheit <- celsius_to_fahrenheit(celsius)
cat(celsius, "°C is equal to", round(fahrenheit, 2), "°F\n")
} else {
cat("Invalid choice! Please enter 1 or 2.\n")
}

2
Result
The R program successfully converts temperatures between Fahrenheit and Celsius based on the
user’s choice.

3
[Link] :2 Find the Area of Rectangle, Square, Circle And Triangle by Accepting
Date : Suitable Input Parameters from User
Aim
To write an R program that calculates the area of a rectangle, square, circle, and triangle by
accepting appropriate input values from the user.
Procedure:
1. Start the program.
2. Display menu options for Rectangle, Square, Circle, and Triangle.
3. Read user choice.
4. Based on the choice:
• Ask the user to enter required input values
(length/breadth, side, radius, base/height).
5. Apply the respective area formula.
6. Display the computed area.
7. End the program.
Program
cat("Area Calculation Program\n")
cat("------------------------\n")
cat("1. Area of Rectangle\n")
cat("2. Area of Square\n")
cat("3. Area of Circle\n")
cat("4. Area of Triangle\n")
choice_input <- readline("Enter your choice (1-4): ")
# Convert safely to integer
choice <- suppressWarnings([Link](choice_input))
if ([Link](choice) || choice < 1 || choice > 4) {
cat("ERROR! Invalid choice. Please enter a number from 1 to 4.\n")
} else if (choice == 1) {
length <- [Link](readline("Enter length: "))
breadth <- [Link](readline("Enter breadth: "))
cat("Area of Rectangle =", length * breadth, "\n")
} else if (choice == 2) {
side <- [Link](readline("Enter side: "))

4
cat("Area of Square =", side * side, "\n")

} else if (choice == 3) {
radius <- [Link](readline("Enter radius: "))
cat("Area of Circle =", pi * radius^2, "\n")
} else if (choice == 4) {
base <- [Link](readline("Enter base: "))
height <- [Link](readline("Enter height: "))
cat("Area of Triangle =", 0.5 * base * height, "\n")
}

Result
The R program successfully calculates the area of different shapes Rectangle, Square, Circle,
and Triangle by accepting appropriate input values from the user.

5
[Link] :3 To Find List of Even Numbers from 1 to N Using R-Loops
Date :
Aim
To write an R program that finds and displays all even numbers from 1 to a user-specified value
n using loop statements.
Procedure:
1. Start the program.
2. Read the value of n from the user using readline().
3. Convert the input value to an integer.
4. Use a for loop to repeat from 1 to n.
5. Inside the loop, check if the number is even using the condition number %% 2 == 0.
6. If the condition is true, print the number.
7. Continue the loop until all numbers up to n are checked.
8. End the program.
Program
n <- [Link](readline("Enter the value of n: "))
cat("Even numbers from 1 to", n, "are:\n")
for (i in 1:n) {
if (i %% 2 == 0) {
cat(i, " ")
}
}
cat("\n")

Result
The R program successfully finds and displays all even numbers from 1 to a user-specified
value n.

6
[Link] :4 Create a Function to Print Squares of Numbers in Sequence
Date :

Aim
To write an R program that defines a function to print the squares of numbers from 1 to n, where
n is provided by the user.
Procedure:
1. Start the program.
2. Define a function (e.g., print_squares) that takes a number n as input.
3. Use a for loop inside the function from 1 to n.
4. Compute the square of each number using i^2.
5. Print each number along with its square.
6. Call the function with the user-provided input.
7. End the program.
Program
# Function to print squares of numbers
printSquares <- function(n) {
for (i in 1:n) {
square <- i^2
cat(i, "squared is", square, "\n")
}
}
# Example usage
printSquares(5)

Result
The R program successfully prints the squares of numbers from 1 to a user-specified number n.

7
[Link] :5 Join Columns and Rows in A Data Frame using cbind() and rbind()
Date :
Aim
To write an R program that demonstrates how to join columns and rows in a data frame using
the functions cbind() (column bind) and rbind() (row bind).
Procedure:
1. Start the program.
2. Create two or more vectors to join as columns.
3. Combine the vectors using cbind() to form a data frame.
4. Create additional rows using vectors.
5. Use rbind() to add the new rows to the existing data frame.
6. Display the final data frame.
7. End the program.
Program
# Creating initial data frames
df1 <- [Link](
ID = c(1, 2, 3),
Name = c("A", "B", "C")
)
df2 <- [Link](
Age = c(25, 30, 22),
Score = c(80, 90, 85)
)
# ---- JOIN COLUMNS USING cbind() ----
cat("Joining columns using cbind():\n")
df_columns_joined <- cbind(df1, df2)
print(df_columns_joined)
# Creating two more data frames with same columns
df3 <- [Link](
ID = c(4, 5),
Name = c("D", "E")
)

8
# ---- JOIN ROWS USING rbind() ----
cat("\nJoining rows using rbind():\n")
df_rows_joined <- rbind(df1, df3)
print(df_rows_joined)

Result
The program successfully demonstrates how to join columns using cbind() to create a data
frame and how to add new rows to it using rbind().

9
[Link] :6 Implement Different String Manipulation Functions
Date :

Aim
To write an R program that demonstrates the use of various string manipulation functions such
as nchar(), toupper(), tolower(), substring(), paste(), and strsplit().
Procedure:
1. Start the program.
2. Create a string variable in R.
3. Apply different string manipulation functions such as:
• nchar() to count characters
• toupper() to convert to uppercase
• tolower() to convert to lowercase
• substring() to extract part of a string
• paste() to join two strings
• strsplit() to split a string
4. Display the output of each function.
5. End the program.
Program
# Sample string
text <- "Hello World"
text2 <- " R Programming Language "
vec <- c("apple", "banana", "cherry")
cat("Original strings:\n")
print(text)
print(text2)
print(vec)
cat("\n1. Convert to Uppercase (toupper):\n")
print(toupper(text))
cat("\n2. Convert to Lowercase (tolower):\n")
print(tolower(text))
cat("\n3. String Length (nchar):\n")
10
print(nchar(text))

cat("\n4. Trim Whitespace (trimws):\n")


print(trimws(text2))
cat("\n5. Substring Extraction (substr):\n")
print(substr(text, 1, 5)) # First 5 characters
cat("\n6. Replace Part of String (sub, gsub):\n")
print(sub("World", "R", text)) # Replace first occurrence
print(gsub("a", "@", vec)) # Replace all occurrences
cat("\n7. Concatenate Strings (paste, paste0):\n")
print(paste("Hello", "R", "World"))
print(paste0("Hello", "_", "R"))
cat("\n8. Split String (strsplit):\n")
print(strsplit(text, " "))
cat("\n9. Find Matching Patterns (grep):\n")
print(grep("a", vec)) # Positions of words containing 'a'
cat("\n10. Extract Matches (regexpr / regexec):\n")
print(regexpr("World", text)) # Starting index
cat("\n11. Format Strings (sprintf):\n")
print(sprintf("The value of pi is %.2f", pi))

Result
The R program successfully demonstrates various string manipulation operations including
character counting, case conversion, substring extraction, string concatenation, and splitting.

11
[Link] :7 Implement Different Data Structures (Vectors, Lists, Data Frames)
Date :
Aim
To write an R program that demonstrates the creation and usage of different data structures such
as vectors, lists, and data frames.
Procedure:
1. Start the program.
2. Create a vector using c() function.
3. Create a list combining different data types and objects.
4. Create a data frame from vectors of equal length.
5. Display all the created data structures.
6. End the program.
Program
cat("=== R Data Structures Demonstration ===\n\n")
# -----------------------------
# 1. VECTORS
# -----------------------------
cat("1. VECTORS\n")
# Creating vectors
num_vec <- c(10, 20, 30, 40)
char_vec <- c("Apple", "Banana", "Cherry")
log_vec <- c(TRUE, FALSE, TRUE)
cat("Numeric Vector:\n")
print(num_vec)
cat("Character Vector:\n")
print(char_vec)
cat("Logical Vector:\n")
print(log_vec)
# -----------------------------
# 2. LISTS
# -----------------------------
cat("\n2. LISTS\n")

12
my_list <- list(
Numbers = num_vec,
Fruits = char_vec,
Flag = log_vec,
Value = 3.14
)
cat("List Contents:\n")
print(my_list)
cat("Access 1st element of list:\n")
print(my_list$Numbers) # Access by name
print(my_list[[1]]) # Access by index
# -----------------------------
# 3. DATA FRAMES
# -----------------------------
cat("\n3. DATA FRAMES\n")
# Creating a data frame
df <- [Link](
ID = c(1, 2, 3),
Name = c("Alice", "Bob", "Charlie"),
Age = c(24, 30, 28)
)
cat("Data Frame:\n")
print(df)
cat("Access specific column (Name):\n")
print(df$Name)
cat("Access row 2:\n")
print(df[2, ])

13
Result
The R program successfully demonstrates the creation and display of three major data
structures: vector, list, and data frame.

14
[Link] :8 To Read a CSV File and Analyze the Data in the File
Date :
Aim
To write an R program to read data from a CSV file and perform basic data analysis such as
viewing the structure, summary, and first few records of the dataset.
Procedure:
1. Start the program.
2. Use the [Link]() function to load the CSV file into a data frame.
3. Display the first few rows using head().
4. Display the structure of the dataset using str().
5. Generate summary statistics using summary().
6. End the program.
Program
# -----------------------------------------
# Read a CSV file
# -----------------------------------------
# Ask user for file name
file_name <- readline("Enter the CSV file name (with .csv extension): ")
# Read CSV
data <- [Link](file_name)
cat("\n=== Data Successfully Loaded ===\n")
print(head(data)) # show first few rows
# -----------------------------------------
# Analyze the Data
# -----------------------------------------

cat("\n1. Structure of the dataset (str):\n")


str(data)

cat("\n2. Summary statistics (summary):\n")


print(summary(data))

15
cat("\n3. Number of rows and columns:\n")
cat("Rows:", nrow(data), "\n")
cat("Columns:", ncol(data), "\n")

cat("\n4. Column names:\n")


print(colnames(data))
cat("\n5. Check for missing values:\n")
print(colSums([Link](data)))
cat("\n6. Display first 10 rows:\n")
print(head(data, 10))
cat("\n7. Display last 10 rows:\n")
print(tail(data, 10))

Result
The R program successfully reads the CSV file and analyzes the dataset by displaying the first
few records, structure of the file, and summary statistics.

16
[Link] :9 Create pie Chart and Bar Chart for a Data Set
Date :
Aim
To write an R program that creates a Pie Chart and a Bar Chart for a given data set using R’s
graphical functions.
Procedure:
1. Start the program.
2. Create a data set (vector) containing values or categories.
3. Use the pie() function to plot a pie chart.
4. Use the barplot() function to plot a bar chart.
5. Add appropriate labels and titles to both charts.
6. Display the charts on the screen.
7. End the program.
Program
# Sample Data
fruits <- c("Apple", "Banana", "Cherry", "Orange")
counts <- c(25, 30, 15, 10)
# -----------------------------
# 1. Pie Chart
# -----------------------------
cat("Creating Pie Chart...\n")
pie(
counts,
labels = fruits,
main = "Fruit Distribution",
col = rainbow(length(fruits))
)
# -----------------------------
# 2. Bar Chart
# -----------------------------
cat("Creating Bar Chart...\n")
barplot(
counts,
17
[Link] = fruits,
main = "Fruit Counts",
xlab = "Fruits",
ylab = "Count",
col = "skyblue",
border = "blue"
)

Result
The R program successfully generates a pie chart and a bar chart for the given data set.

18
[Link] :10 Create a Data Set and do Statistical Analysis on the Data
Date :
Aim
To create a data set in R and perform basic statistical analysis such as mean, median, mode,
variance, standard deviation, minimum, maximum, and summary.
Procedure:
1. Start the program.
2. Create a numeric data set using a vector.
3. Use built-in functions such as:
• mean() to find average
• median() to find middle value
• summary() for quick statistics
• sd() for standard deviation
• var() for variance
• min() and max() for range
4. Print all results.
5. End the program.
Program
# -----------------------------
# 1. Create Dataset
# -----------------------------
# Sample dataset of students
students <- [Link](
ID = 1:10,
Name = c("Alice", "Bob", "Charlie", "David", "Eva",
"Frank", "Grace", "Helen", "Ian", "Julia"),
Age = c(20, 22, 21, 23, 20, 22, 21, 23, 22, 21),
Marks = c(85, 90, 78, 92, 88, 76, 95, 89, 84, 91)
)

cat("=== Dataset ===\n")


print(students)
19
# -----------------------------
# 2. Statistical Analysis
# -----------------------------
cat("\n1. Structure of dataset:\n")
str(students)

cat("\n2. Summary Statistics:\n")


print(summary(students))

cat("\n3. Mean, Median, and Standard Deviation of Marks:\n")


mean_marks <- mean(students$Marks)
median_marks <- median(students$Marks)
sd_marks <- sd(students$Marks)

cat("Mean Marks:", mean_marks, "\n")


cat("Median Marks:", median_marks, "\n")
cat("Standard Deviation:", sd_marks, "\n")

cat("\n4. Minimum and Maximum Marks:\n")


cat("Min:", min(students$Marks), "\n")
cat("Max:", max(students$Marks), "\n")

cat("\n5. Variance of Marks:\n")


print(var(students$Marks))

cat("\n6. Correlation between Age and Marks:\n")


print(cor(students$Age, students$Marks))

cat("\n7. Frequency table of Age:\n")


print(table(students$Age))
20
Result
The R program successfully creates a dataset and performs statistical analysis.

21
[Link] :11 To Find Factorial of the Given Number using Recursive Function
Date :

Aim
To write an R program that finds the factorial of a given number using a recursive function.
Procedure:
1. Start the program.
2. Define a recursive function factorial() that:
• returns 1 if the number is 0 or 1
• otherwise multiplies the number by factorial(number − 1)
3. Read a number from the user.
4. Call the recursive function with the user’s input.
5. Display the factorial value.
6. End the program.
Program
# Recursive function to calculate factorial
factorial_recursive <- function(n) {
# Validate input type
if (![Link](n) || n != floor(n)) {
stop("Error: Input must be a non-negative integer.")
}

# Factorial is undefined for negative numbers


if (n < 0) {
stop("Error: Factorial is not defined for negative numbers.")
}

# Base case: factorial of 0 or 1 is 1


if (n == 0 || n == 1) {
return(1)
}
22
# Recursive case
return(n * factorial_recursive(n - 1))
}

# ---- Main Program ----


# Read input from user
cat("Enter a non-negative integer: ")
user_input <- suppressWarnings([Link](readline()))

# Try to compute factorial with error handling


result <- tryCatch({
fact <- factorial_recursive(user_input)
cat("Factorial of", user_input, "is:", fact, "\n")
}, error = function(e) {
cat(e$message, "\n")
})

Result
The program successfully computes the factorial of a given number using a recursive function
and displays the correct output.

23
[Link] :12 Count the number of even and odd numbers from array of N numbers
Date :
Aim
To write a program to count the number of even and odd numbers from an array of N
numbers provided by the user.
Procedure:
1. Read how many numbers (N) the user wants to enter.
2. Get all the N numbers from the user.
3. Set two counters: even = 0, odd = 0.
4. Check each number:
• If number % 2 == 0 → increase even
• Else → increase odd
5. Display the count of even numbers and count of odd numbers.
Program
# Function to count even and odd numbers in a numeric vector
# Ask user for the number of elements
n_input <- readline("Enter the number of elements (N): ")
n <- suppressWarnings([Link](n_input))

if ([Link](n) || n < 1) {
cat("ERROR! Please enter a valid positive integer.\n")
} else {
# Initialize an empty vector
arr <- numeric(n)

# Take input for each element


for (i in 1:n) {
num_input <- readline(paste("Enter number", i, ": "))
num <- suppressWarnings([Link](num_input))
if ([Link](num)) {
cat("Invalid input! Please enter a number.\n")
i <- i - 1 # Repeat this iteration
24
} else {
arr[i] <- num
}
}

# Count even and odd numbers


even_count <- sum(arr %% 2 == 0)
odd_count <- sum(arr %% 2 != 0)

# Display results
cat("\nArray of numbers:\n")
print(arr)

cat("\nNumber of even numbers:", even_count, "\n")


cat("Number of odd numbers:", odd_count, "\n")
}

Result
The program successfully counts and displays the number of even and odd numbers from the
given array of N numbers provided by the user.

25

You might also like