0% found this document useful (0 votes)
19 views37 pages

R Programming Practical Exercises Guide

Uploaded by

malihamryam12
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)
19 views37 pages

R Programming Practical Exercises Guide

Uploaded by

malihamryam12
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

[Link].

Date List Of the Practical Page Staff


No. Signature
Program to convert the given temperature from
1. Fahrenheit to Celsius and vice versa depending
upon user’s choice.
Program to find the area of rectangle, square,
2. circle, and triangle by accepting suitable input
parameters from user.
Write a program to find list of even numbers
3. from 1 to n using R Loops.

Create a function to print squares of numbers in


4. sequence.

Write a program to join columns and rows in a


5. data frame using cbind () and rbind () in R.

Implement different String Manipulation


6. functions in R.

Implement different data structures in R


7. (Vectors, Lists, Data Frames).

Write a program to read a csv file and analyze


8. the data in the file in R.

Create pie chart and bar chart using R.


9.

Create a data set and do statistical analysis on


10. the data using R.

Program to find factorial of the given number


11. using recursive function.

Write a R program to count the number of even


12. and odd numbers from array of N numbers.
Ex. No. 01
Convert the given Temperature from Fahrenheit to
Date
Celsius and Vice Versa

Aim:

Implementing a program to convert the given temperature from Fahrenheit to Celsius and
vice versa depending upon user’s choice.

Procedure:

• Open RStudio and create a new R Script file, then save the file with an appropriate name.

• In the script editor, type the R function code for temperature conversion, including asking

the user for a choice (1 for F to C, 2 for C to F) using readline ().

• Inside the function, use an if statement, if choice is "1", calculate Celsius and print the

result. If choice is "2", calculate Fahrenheit and print the result.

• Add an else part to handle invalid choices.

• After defining the function, call the function to run the program.

• Enter the required inputs in the console when prompted and exit the program.
Source Code:

convert_temp <- function () {


choice <- readline("Enter 1 to convert F to C, 2 to convert C to F: ")
temp <- [Link](readline("Enter temperature: "))
if (choice == "1") {
celsius <- (temp - 32) * 5/9 cat("Temperature in Celsius:", celsius, "\n")
} else if (choice == "2") {
fahrenheit <- (temp * 9/5) + 32
cat("Temperature in Fahrenheit:", fahrenheit, "\n")
} else {
cat("Invalid choice\n")
}
}
convert_temp()

Result:
Thus, the above R program has been executed successfully.
Output:

Enter 1 to convert F to C, 2 to convert C to F: 1

Enter temperature: 212

Temperature in Celsius: 100

Enter 1 to convert F to C, 2 to convert C to F: 2

Enter temperature: 100

Temperature in Fahrenheit: 212


Ex. No. 02
Find the Area of Rectangle, Square, Circle, and Triangle
Date
by Accepting Suitable Input Parameters

Aim:

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

Procedure:

• Open RStudio and create a new R Script file, then save the file with an appropriate name.

• Write the area calculation function, that asks the user to choose a shape (rectangle,

square, circle, triangle).

• Read the dimensions based on the selected shape and use if-else if chain to calculate and

display the area for each shape.

• Save the script with a proper name and run the program.

• When prompted,

✓ If user entered rectangle, then length=10, breadth=5 (expected: 50)

✓ If user entered square, then side=4 (expected: 16)

✓ If user entered circle, then radius=3 (expected: ~28.27)

✓ If user entered triangle, then base=10, height=6 (expected: 30)


Source Code:
find_area <- function() {
choice <- readline("Choose shape (rectangle, square, circle, triangle): ")

if (choice == "rectangle") {
l <- [Link](readline("Enter length: "))
b <- [Link](readline("Enter breadth: "))
cat("Area of Rectangle:", l * b, "\n")
} else if (choice == "square") {
s <- [Link](readline("Enter side: "))
cat("Area of Square:", s^2, "\n")
} else if (choice == "circle") {
r <- [Link](readline("Enter radius: "))
cat("Area of Circle:", pi * r^2, "\n")
} else if (choice == "triangle") {
b <- [Link](readline("Enter base: "))
h <- [Link](readline("Enter height: "))
cat("Area of Triangle:", 0.5 * b * h, "\n")
} else {
cat("Invalid shape\n")
}
}
find_area()

Result:

Thus, the above R program has been executed successfully.


Output:

Choose shape (rectangle, square, circle, triangle): rectangle

Enter length: 10
Enter breadth: 5
Area of Rectangle: 50
Ex. No. 03
List of Even Numbers from 1 to n using R Loops
Date

Aim:

Write a program to find list of even numbers from 1 to n using R Loops.

Procedure:

• Open RStudio and create a new R Script file, then save the file with an appropriate name.

• Write a program that reads a positive integer from user and use a for loop with modulo

operator (%%) to find even numbers.

• The program stores even numbers in a vector and prints the final list.

• Save the script with a proper name and run the program.
Source Code:
cat("This program finds all even numbers from 1 to your chosen number.\n\n")
n <- [Link](readline("Enter a positive whole number: "))
even_numbers <- c()
for (i in 1:n) {
if (i %% 2 == 0) {
cat("Found even number:", i, "\n")
even_numbers <- c(even_numbers, i)
}
}
cat("\nThe even numbers from 1 to", n, "are:\n")
print(even_numbers)

Result:
Thus, the above R program has been executed successfully.
Output:

This program finds all even numbers from 1 to your chosen number.

Enter a positive whole number: 10


Found even number: 2

Found even number: 4

Found even number: 6

Found even number: 8

Found even number: 10

The even numbers from 1 to 10 are:

[1] 2 4 6 8 10
Ex. No. 04
A Function to Print Squares of Numbers in Sequence
Date

Aim:
To create a function to print squares of numbers in sequence.

Procedure:

• Open RStudio and create a new R Script file, then save the file with an appropriate name.

• Write a program that prints squares that defines print_squares () function using for loop

and sprint () to display squares.

• Uses repeat loop with input validation and continues asking for input until valid positive

integer is entered.

• Save the script with a proper name and run the program.
Source Code:
print_squares <- function(n) {
cat("Number of squares you like to see is ", n, ":\n")
for (i in 1:n) {
cat(sprintf("Number %d squared is %d \n", i, i^2))
}
}
repeat {
user_input <- readline(prompt = "Enter any positive number to square: ")
user_num <- [Link](user_input)
if (![Link](user_num) && user_num > 0) {
print_squares(user_num)
break
}
else {
cat("Invalid input. Please enter a valid positive integer.\n")
}
}

Result:
Thus, the above R program has been executed successfully.
Output:

Enter any positive number to square: 4

Number of squares you like to see is 4 :

Number 1 squared is 1
Number 2 squared is 4

Number 3 squared is 9

Number 4 squared is 16
Ex. No. 05
Joining Columns and Rows in a Data Frame using cbind
Date
() and rbind () in R

Aim:

To write a program that joins the columns and rows in a data frame using cbind () and rbind
() in R.

Procedure:

• Open RStudio and create a new R Script file, then save the file with an appropriate name.

• Write a program that creates a data frame with ID and Name columns using [Link] (),

adds Age column using cbind (), and adds new student row using rbind () with new data

frame.

• Save the script with a proper name and run the program in RStudio.
Source Code:
students <- [Link](
ID = c(01, 02, 03),
Name = c("S", "M", "M"))
cat("Original students data frame:\n")
print(students)
ages <- c(19, 20, 21)
students <- cbind(students, Age = ages)
cat("\nAdded Age column:\n")
print(students)
new_student <- [Link](ID = 04, Name = "A", Age = 22)
students <- rbind(students, new_student)
cat("\nAfter adding a new student row:\n")
print(students)

Result:
Thus, the above R program has been executed successfully.
Output:

Original students data frame:

ID Name
1 1 S
2 2 M
3 3 M

Added Age column:

ID Name Age
1 1 S 19
2 2 M 20
3 3 M 21

After adding a new student row:

ID Name Age
1 1 S 19
2 2 M 20
3 3 M 21
4 5 A 22
Ex. No. 06
String Manipulation Functions in R
Date

Aim:
To write a program that implements different string manipulation functions in R.

Procedure:

• Open RStudio and create a new R Script file, then save the file with an appropriate name.

• Write a program that defines a sample string.

• Use various string manipulation functions: toupper() for uppercase, tolower() for
lowercase, nchar() for string length, substr() to extract a substring, sub() to replace a part
of the string, and strsplit() to split the string into words.

• Display the results of each operation.

• Save the script with a proper name and run the program in RStudio.
Source Code:

text <- "Hello, R Language is Powerful!"

cat("Original text:\n", text, "\n\n")

cat("Upper case:\n", toupper(text), "\n")


cat("Lower case:\n", tolower(text), "\n")

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

cat("Extract substring (chars 8 to 18):", substr(text, 8, 18), "\n")

cat("Replace 'Powerful' with 'Amazing':", sub("Powerful", "Amazing", text), "\n")

cat("Splitting words:\n")

words <- strsplit(text," ")[[1]]

print(words)

Result:
Thus, the above R program has been executed successfully.
Output:

Original text:

Hello, R Language is Powerful!

Upper case:
HELLO, R LANGUAGE IS POWERFUL!

Lower case:

hello, r language is powerful!

Number of characters: 26

Extract substring (chars 8 to 18): R Language

Replace 'Powerful' with 'Amazing': Hello, R Language is Amazing!

Splitting words:

[1] "Hello," "R" "Language" "is" "Powerful!"


Ex. No. 07
Data Structures in R (Vectors, Lists, Data Frames)
Date

Aim:
To write a program that implements different data structures in R, such as vectors, lists, and data
frames.
Procedure:
• Open RStudio and create a new R Script file, then save the file with an appropriate name.
• Write a program that creates and displays a vector containing a sequence of numbers.
• Create a list with mixed elements (a character string, a numeric vector, and a logical
value) and display it.
• Create a data frame with columns for StudentID, Name, and Score, and display it.
• Save the script with a proper name and run the program in RStudio.
Source Code:
vec <- c(5, 10, 15, 20)
cat("Vector example:\n")
print(vec)
lst <- list(
name = "Alex",
scores = c(90, 85, 88),
graduated = TRUE
)
cat("\nList example with mixed elements:\n")
print(lst)
df <- [Link](
StudentID = c(1, 2, 3),
Name = c("Billie", "Karen", "Carol"),
Score = c(88, 92, 95)
)
cat("\nData frame example:\n")
print(df)

Result:
Thus, the above R program has been executed successfully.
Output:

Vector example:

[1] 5 10 15 20

List example with mixed elements:


$name

[1] "Alex"

$scores

[1] 90 85 88

$graduated

[1] TRUE

Data frame example:

StudentID Name Score

1 1 Billie 88

2 2 Karen 92

3 3 Carol 95
Ex. No. 08
Read a CSV file and analyze the data in the file in R
Date

Aim:
To write a program that reads a CSV file and analyzes the data within it using R.
Procedure:
• Open RStudio and create a new R Script file, then save the file with an appropriate name.
• Write a program that asks the user to enter the name of a CSV file.
• Read the CSV file into a data frame using [Link]().
• Display the first 6 rows of the data using head().
• Show the structure of the data using str() and summary statistics using summary().
• Calculate and display the means of any numeric columns found in the data frame.
• Save the script with a proper name and run the program in RStudio.
Source Code:
cat("Reading your CSV file into R...\n")
file_path <- readline("Please enter the CSV file name (with extension): ")
data <- [Link](file_path, stringsAsFactors = FALSE)
cat("First 6 rows of your data:\n")
print(head(data))
cat("\nData structure overview:\n")
str(data)
cat("\nSummary Statistics:\n")
print(summary(data))
num_cols <- sapply(data, [Link])
if (any(num_cols)) {
cat("\nMeans of numeric columns:\n")
print(sapply(data[, num_cols], mean, [Link] = TRUE))
} else {
cat("\nNo numeric columns found for mean calculation.\n")
}

Result:
Thus, the above R program has been executed successfully.
Output:

Reading your CSV file into R...

Please enter the CSV file name (with extension): [Link]

First 6 rows of your data:


ID Name Marks Age

1 1 John 85 20

2 2 Sarah 90 19

3 3 Mike 78 21

4 4 Emma 92 20

5 5 Dave 88 22

Data structure overview:

'[Link]': 5 obs. of 4 variables:


$ ID : int 1 2 3 4 5

$ Name : chr "John" "Sarah" "Mike" "Emma" ...

$ Marks: int 85 90 78 92 88

$ Age : int 20 19 21 20 22

Summary Statistics:

ID Name Marks Age

Min. :1.0 Length:5 Min. :78.00 Min. :19.00


1st Qu.:2.0 Class :character 1st Qu.:85.00 1st Qu.:20.00

Median :3.0 Mode :character Median :88.00 Median :20.00

Mean :3.0 Mean :86.60 Mean :20.40

3rd Qu.:4.0 3rd Qu.:90.00 3rd Qu.:21.00

Max. :5.0 Max. :92.00 Max. :22.00

Means of numeric columns:

ID Marks Age
3.000000 86.600000 20.400000
Ex. No. 09
Pie chart and Bar chart using R
Date

Aim:
To write a program that creates a pie chart and a bar chart using R.
Procedure:
• Open RStudio and create a new R Script file, then save the file with an appropriate
name.
• Write a program that defines data for categories and their corresponding values
(e.g., market share).
• Use the pie() function to create a pie chart with labels, a main title, and colors.
• Use the barplot() function to create a bar chart with category names, a title, axis
labels, and color.
• Save the script with a proper name and run the program in RStudio.
Source Code:
categories <- c("Android", "iOS", "Windows", "Other")
market_share <- c(70, 20, 7, 3)
cat("Creating a pie chart of Market Share...\n")
pie(market_share, labels = categories, main = "Mobile OS Market Share", col =
rainbow(length(categories)))
cat("Creating a bar chart of Market Share...\n")
barplot(market_share, [Link] = categories, col = "lightblue",
main = "Mobile OS Market Share", ylab = "Percentage")

Result:
Thus, the above R program has been executed successfully.
Output:
Ex. No. 10
Create a data set and do statistical analysis on the data
Date using R

Aim:
To write a program that creates a data set and performs statistical analysis on it using R.
Procedure:
• Open RStudio and create a new R Script file, then save the file with an appropriate name.
• Write a program that creates a numeric vector representing a dataset (e.g., scores).
• Display the dataset.
• Calculate and print the mean, median, variance, standard deviation, minimum, and
maximum values of the dataset using appropriate R functions (mean(), median(), var(),
sd(), min(), max()).
• Save the script with a proper name and run the program in RStudio.
Source Code:
scores <- c(68, 75, 80, 85, 90, 95, 100, 85)
cat("Analyzing the following scores:\n")
print(scores)
cat("\nMean score:", mean(scores), "\n")
cat("Median score:", median(scores), "\n")
cat("Variance:", var(scores), "\n")
cat("Standard Deviation:", sd(scores), "\n")
cat("Minimum score:", min(scores), "\n")
cat("Maximum score:", max(scores), "\n")

Result:
Thus, the above R program has been executed successfully.
Output:

Analyzing the following scores:

[1] 68 75 80 85 90 95 100 85

Mean score: 84.75

Median score: 85

Variance: 98.07143

Standard Deviation: 9.903702

Minimum score: 68

Maximum score: 100


Ex. No. 11
Find Factorials of the given Number using Recursive
Date Function

Aim:
To write a program that calculates the factorial of a given non-negative integer using a recursive
function in R.
Procedure:
• Open RStudio and create a new R Script file, then save the file with an appropriate name.
• Write a program that defines a recursive function factorial_recursive that takes an integer
n as input.
• Inside the function, implement the base cases: if n is 0 or 1, return 1.
• For other values of n, implement the recursive step: return n multiplied by the factorial of
n-1.
• Prompt the user to enter a non-negative integer using readline() and convert it to an
integer.
• Check if the entered number is negative. If so, print an appropriate message.
• If the number is non-negative, call the factorial_recursive function and print the result.
• Save the script with a proper name and run the program in RStudio.
Source Code:
factorial_recursive <- function(n) {
if (n == 0 || n == 1) {
return(1)
} else {
return(n * factorial_recursive(n - 1))
}
}
num <- [Link](readline("Enter a non-negative integer to find its factorial: "))
if (num < 0) {
cat("Factorial is not defined for negative numbers.\n")
} else {
result <- factorial_recursive(num)
cat("Factorial of", num, "is:", result, "\n")
}

Result:
Thus, the above R program has been executed successfully.
Output:

Enter a non-negative integer to find its factorial: 5

Factorial of 5 is: 120


Ex. No. 12
Program to Count the Number of Even and Odd
Date Numbers from Array of N Numbers.

Aim:
To write an R program that counts the number of even and odd numbers from an array of N
numbers entered by the user.
Procedure:
• Open RStudio and create a new R Script file, then save the file with an appropriate name.
• Write a program that asks the user for the number of elements (N) they want to input.
• Use a loop to accept N numbers from the user and store them in a vector.
• Count the number of even numbers using the modulo operator (%% 2 == 0) and sum().
• Count the number of odd numbers using the modulo operator (%% 2 != 0) and sum().
• Display the entered numbers and the counts of even and odd numbers.
• Save the script with a proper name and run the program in RStudio.
Source Code:
n <- [Link](readline("How many numbers would you like to input? "))
numbers <- integer(n)
cat("Please enter your numbers one by one:\n")
for (i in 1:n) {
numbers[i] <- [Link](readline(paste("Number", i, ": ")))
}
even_count <- sum(numbers %% 2 == 0)
odd_count <- sum(numbers %% 2 != 0)
cat("You entered:\n"); print(numbers)
cat("Count of even numbers:", even_count, "\n")
cat("Count of odd numbers:", odd_count, "\n")

Result:
Thus, the above R program has been executed successfully.
Output:
How many numbers would you like to input? 5
Please enter your numbers one by one:
Number 1: 2
Number 2: 3
Number 3: 4
Number 4: 7
Number 5: 8
You entered:
[1] 2 3 4 7 8
Count of even numbers: 3
Count of odd numbers: 2

You might also like