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

R Programming Laboratory Manual

Uploaded by

reallychek12345
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)
11 views53 pages

R Programming Laboratory Manual

Uploaded by

reallychek12345
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

Department Name

Laboratory Manual
(Name of the Programme, Semester, Course and Code)
_____________________________________________________________________________________________

Table of Contents

Experiment/Lab Name of the Experiment/Activity/Exercise Page


Exercise/Activity No. Number(s)
1 Download and install R-Programming environment and install basic 9
packages using [Link]() command in R.
2 Write an R script to take input from the user (name, age, and marks) 11
and print them with proper formatting.
3 Write a program to demonstrate the use of NA, Inf, and -Inf in 14
calculations and explain their significance.
4 Create a numeric vector of 10 elements and perform the following 16
operations:

• Calculate the sum & mean of the vector.


• Access the 3rd and 5th elements of the vector.

Create a list containing:

• Your name, age, and a vector of your five favorite


numbers.
• Add a new element to the list (e.g., "Favorite Color").

5 Write an R program to: 18

Create a 3x3 matrix with numbers from 1 to 9 and perform:

o Transpose of the matrix.


o Row-wise and column-wise sums.

Create a 2x2x3 array with numbers from 1 to 12, name its rows,
columns, and dimensions, and access specific elements.
6 19

Write an R program to:


1. Assign values to three variables (a, b, c) using different
assignment operators.
2. Demonstrate the use of arithmetic, relational, logical, and
miscellaneous operators in R.

7 Write an R program to: 21

1. Check if a number entered by the user is positive, negative,


or zero using if-else.
2. Use a for loop to print the first 10 natural numbers.
3. Use a while loop to calculate the factorial of a given
number.
4. Demonstrate the use of break and next statements in a
repeat loop.

8 [Link] a vector of numbers from 1 to 10. 23

1. Calculate the mean(), sum(), min(), and max() of the


vector.
2. Generate a sequence from 5 to 50 with a step of 5 using
seq().
3. Concatenate the numbers and print them as a single string
using paste().

[Link] a script to manipulate the string "Brainware


University".

1. Extract the substring "Brainware" using substr().


2. Split the string into individual words using strsplit().
3. Convert the entire string to uppercase and lowercase using
toupper() and tolower().

create a vector using seq() from 1 to 20. Write a program to: 25

1. Repeat the vector three times using rep().


2. Access the first 5 elements of the vector.
3. Demonstrate vector recycling by adding this vector to
another vector of length 5.

9 Create a list in R to store:


1. Your name (character), age (numeric), and grades (numeric
vector).
2. Add an element to the list (e.g., "Hobby").
3. Remove the age element from the list.
4. Convert the list into a vector and display the result.
5. Merge the two lists into a single list.

Create a 3x3 matrix with values from 1 to 9.

6. Perform matrix addition and multiplication with another


matrix of the same dimensions.
7. Access and print the element in the second row, third
column.
8. Calculate the row-wise and column-wise sums.

10
Create a 2x3x2 array with values from 1 to 12.

1. Name the rows as "Row1", "Row2", and columns as


"Col1", "Col2", "Col3".
2. Access the elements in the first row and second column of
the second layer.
3. Replace all elements greater than 6 with NA.

Create a factor using the vector c("Red", "Blue", "Green",


"Red", "Blue").

1. Display the levels of the factor.


2. Generate a factor with 3 levels ("High", "Medium", "Low")
repeated 4 times using gl().
3. Modify the factor to include a new level "Very High".

11 Write a script to process the text "R Programming is Fun and


Challenging".

1. Extract every second word from the sentence.


2. Count the number of occurrences of vowels (a, e, i, o,
u) in the string.
3. Replace the word "Challenging" with "Exciting".

• Create a nested list containing:

1. A data frame with student names, marks, and grades.


2. A vector with the total marks for each student.
3. A list of factors indicating the performance category
("Excellent", "Good", "Average").

• Write a script to:

1. Access and modify the data frame inside the nested list.
2. Add a new entry for a student.
3. Extract students with "Excellent" performance.

12 Create a factor of fruit names c("Apple", "Banana",


"Orange", "Apple", "Banana").

1. Find and display the frequency of each fruit.


2. Drop the level "Orange" from the factor and display the
updated factor.

Create a 2x3x2 array with values from 1 to 12. Write a program to:

1. Name the rows, columns, and dimensions of the array.


2. Access a specific element (e.g., row 1, column 2,
dimension 1).
3. Calculate the sum of all elements in the array.

13

Write an R script to:

1. Create a data frame with the following columns:


Name, Age, Marks.
2. Display the structure of the data frame using str().
3. Use dim(), nrow(), and ncol() to find its
dimensions, number of rows, and columns.
4. View the first and last few rows using head() and
tail().
• Create a data frame with columns: "Name", "Age", and "Score"
and display it.
• Access the following from the data frame you created:

• All rows of the "Name" column.


• The first row of the data frame.
• The "Age" and "Score" columns for the first two rows.

• Apply the following functions to your data frame and interpret


the output:

• dim()
• nrow()
• ncol()
• str()
• summary()
• names()
• head()
• tail()

14 • Add a new column, "Grade", to your data frame with values


"A", "B", "A".
• Add a new row to your data frame with the details of another
student.
• Combine two data frames with identical columns using
rbind().
• Add a new column, "Hobbies", to your data frame using
cbind().

• Merge two data frames using a common column ("ID") and


display the result.
15
• Use the melt() function to reshape your data frame into a long
format and display the result.
• Use the dcast() function to reshape the melted data back into a
wide format.
16. • Check your current working directory using getwd() and list all
files in it using dir().
• Save your data frame to a CSV file named "[Link]". Then read
the file back into R and analyze it using:

• summary()
• min()
• max()
• mean()
• median()
Write your data frame to an Excel file and then read it back into
R. Display the contents of the Excel file.
17.
1. Perform the following mathematical operations using R:
a) Addition, subtraction, multiplication, and division of two
numbers.
b) Calculate the square root, factorial, and exponential of a
number.
c) Compute the sine, cosine, and tangent of an angle in both
degrees and radians.
[Link] the following mathematical expression in R:
(3𝑥 2 +5𝑥+2)
, for 𝑥 = 1, 2, … , 10.
𝑥 2 +1
3. Use R to calculate the following for a given vector of numbers:
a) Sum and product of all elements.
b) Mean, median, and standard deviation.
18. [Link] a dataset in R and calculate the following for a numerical 49
column:
a) Mean, median, and mode.
b) Variance, standard deviation, and range.
[Link] the summary() function to generate descriptive statistics for
an entire data frame.
3. Create a box plot for a numerical column in a dataset and
identify any outliers.

19. [Link] R to generate the frequency distribution of a categorical 51


variable.
[Link] a histogram for a numerical column in a dataset. Analyze
and interpret the shape of the histogram (e.g., skewness, modality).
20 53
[Link] a dataset to a CSV file and read it back into R. Display the
contents of the loaded data.
2. Load an Excel file into R using an appropriate library and
display its content.
[Link] an R script to load a CSV file, convert it into a data frame,
and display its content.
[Link] a text file containing tab-delimited data into R and convert
it into a data frame.
5. Save a subset of a data frame to a new CSV file with a different
name.
21 [Link] the following plots using a dataset in R:
a) Line plot for numerical data.
b) Scatter plot between two variables.
c) Bar chart for categorical data.
d) Histogram for numerical data.
2. Customize the visualizations created in question 14 by adding:
a) Titles, axis labels, and legends.
b) Different colors and line types for the plots.
22
[Link] a pie chart to represent the proportion of categories in a
dataset.
Use the ggplot2 package to create the following:
a) A scatter plot with a regression line.
b) A grouped bar chart for categorical data.

[Link] a heatmap for a correlation matrix using a dataset in R.

23 1. Compute the covariance between multiple pairs of numerical


variables in a dataset.
2. Calculate the correlation coefficient between two numerical
columns in a dataset.
24 1. Create a correlation matrix for a dataset and visualize it using a
heatmap.

2. Interpret the strength and direction of relationships between


variables based on the correlation values obtained.

25 [Link] a simple linear regression analysis using a dataset. Use


one numerical variable as the independent variable and another as
the dependent variable.

2. Plot the regression line obtained from the model on a scatter


plot.
26. [Link] the regression model output and interpret the following:
a) R-squared value.
b) Coefficients of the regression equation.
c) p-values of the model terms.
27. [Link] a multiple linear regression model using a dataset with at
least two predictor variables.
2. Evaluate the model using the Adjusted R-squared value and
residual plots.
[Link] the model to predict outcomes for new data points.
28. [Link] a regression model using a training dataset. Use it to
predict outcomes for a test dataset.

[Link] the prediction accuracy of the model using the


following metrics:
a) Mean Absolute Error (MAE).
b) Root Mean Squared Error (RMSE).
29. [Link] a logistic regression model to classify data into two
categories (e.g., pass/fail).

[Link] the logistic regression model output, including:


a) Odds ratios.
b) Coefficients of the model.

Use the model to predict outcomes for a test dataset and evaluate its
accuracy using a confusion matrix.
30 1. Implement a k-Nearest Neighbors (kNN) classification model
on a dataset. Evaluate the classification performance.
2. Build a decision tree model using a dataset. Visualize the tree
structure.
3. Evaluate the classification models using the following metrics:
a) Precision.
b) Recall.
c) F1-Score.
31 1. Use the mtcars dataset to predict miles per gallon (mpg) based
on the weight (wt) of the car.

[Link] the model using R-squared and residual plots.


32 [Link] the Boston dataset from the MASS package to predict medv
(median home value) based on lstat (percentage of lower status
population). Evaluate the residuals and R-squared value.

33 Perform correlation analysis on the mtcars dataset to identify which


variables have the highest correlation with mpg. Use these variables in a
linear regression model.
34 Extend the above model to include horsepower (hp) and the
number of cylinders (cyl) as additional predictors. Analyze the
significance of each predicto
35 Fit a polynomial regression model to predict mpg based on wt and
visualize the results with a smooth curve.
36 Perform stepwise regression on the mtcars dataset to identify the best
subset of predictors for predicting mpg.
37 Use the Titanic dataset to build a logistic regression model that
predicts survival (Survived) based on age, gender, and class.
38. Use the rpart package to build a decision tree classifier for the iris
dataset, predicting the species of flowers.
39. Train a Random Forest classifier on the iris dataset using the
randomForest package and evaluate its accuracy.

40 Use the class package to build a KNN classifier for the iris dataset.
Experiment with different values of k.
41. Build an SVM classifier on the iris dataset using the package and
visualize the decision boundary.
42. Compare classification models (e.g., logistic regression, decision tree,
SVM) on the iris dataset using metrics such as accuracy, precision,
recall, and F1 score.
43. Use the AirPassengers dataset to fit a linear regression model with
time as the predictor variable and passenger count as the response.
Identify trends and seasonality.
44. Create new features (e.g., interaction terms, polynomials) from the
predictors in mtcars and evaluate their impact on predicting mpg.

45. Create your own small dataset (e.g., test scores vs. hours studied) and
fit a linear regression model. Use this for teaching or practice.

Experiment No 1

1. Aim/Purpose of the Experiment: To set up the R programming environment and install basic packages for

R programming using the [Link]() function.

Learning Outcomes: • Understand how to use R as a calculator.

• Perform basic arithmetic operations in R.

Prerequisites: • Basic knowledge of arithmetic operators: +, -, *, /.

• R environment installed and set up.


Materials/Equipment/Apparatus / Devices/Software required: R programming software or RStudio.

Introduction and Theory: R can be used for basic mathematical operations. The following arithmetic
operators are supported:

• Addition: +
• Subtraction: -
• Multiplication: *
• Division: /
Operating Procedure: • Open R or RStudio.

• In the R console or script editor, type and execute the following commands

Run the code and observe the output.

Precautions and/or Troubleshooting: • Ensure that you use valid numbers for division to avoid dividing by
zero.
1. • Enclose your operations within parentheses for clarity if combining multiple operations.
2. Observations: Results of each arithmetic operation are displayed in the console.

Calculations & Analysis : For example:

• Addition: 10+5=1510 + 5 = 1510+5=15


• Subtraction: 10−5=510 - 5 = 510−5=5
• Multiplication: 10×5=5010 \times 5 = 5010×5=50
• Division: 10÷5=210 \div 5 = 210÷5=2

3. Result & Interpretation : The program demonstrates how R can perform basic arithmetic operations

effectively.

Follow-up Questions : • What happens if you divide by zero in R?

• How can you perform multiple operations in one line?

.Extension and Follow-up Activities (if applicable):

• Explore additional arithmetic operations like modulus (%%) and integer division (%/%).
• Write a program to calculate the area of a rectangle using multiplication.
• Combine arithmetic operations with variables.

Assessments :

• Execute the code in R and verify the results for correctness.


• Modify the code to include other values and validate the outputs.

Suggested readings : • Basic Math in R.

• R Documentation: ?Arithmetic.
Experiment2

1. Aim:

To create an R script that takes user input for name, age, and marks, and prints them in a formatted
manner.

2. Learning Outcomes:

• Understand how to take input from the user in R.


• Learn how to format and print the output in R.

3. Prerequisites:

• Basic understanding of R syntax.


• Familiarity with the readline() function for taking user input.

4. Materials:

• R or RStudio installed on your system.

5. Introduction and Theory:

R provides the readline() function for interactive user input. The input collected through readline() is
of type character and needs to be converted to numeric or integer for calculations.

Key functions:

• readline(prompt = "Your prompt here"): Takes user input as a string.


• [Link](): Converts input to a numeric type.
• cat(): Outputs text with formatting.

6. Operating Steps:
Step 1: Create an R Script

1. Open your preferred text editor or RStudio and create a new script file (input_formatting.R).

Step 2: Write the Script

Step 3: Run the Script

1. Save the script file.


2. Run the script in R or RStudio console.

Step 4: Input Example

7. Precautions:

• Ensure the input for age and marks is numeric.


• Use [Link]() for type conversion, and handle errors if input is not valid.

8. Observations:

• Input is taken interactively using readline().


• Output is displayed with proper formatting using cat().

9. Calculations:

No calculations are needed for this task.

10. Results and Interpretation:

The script successfully takes user input for name, age, and marks and displays it in a well-formatted
structure.

11. Follow-Up Questions:

1. How can you validate that the user entered a numeric value for age and marks?
2. How can you modify the script to save the input to a file?
12. Extension and Follow-Up Activities:

1. Add error handling to ensure numeric inputs for age and marks.
2. Modify the script to calculate and display the grade based on marks.

13. Assessments:

• Verify the output format with different inputs.


• Test the script for both valid and invalid inputs.

14. Suggested Readings:

• R readline() Function Documentation


• ?cat in R for formatting output.

Experiment:

Aim:

To write an R script that demonstrates the use of NA, Inf, and -Inf in calculations and explains their
significance.

2. Learning Outcomes:

• Understand the behavior of NA, Inf, and -Inf in calculations.


• Learn how R handles missing and infinite values during computations.

3. Prerequisites

• Knowledge of basic arithmetic operations in R.


• Understanding of missing values (NA) and special numerical values (Inf, -Inf).

4. Materials:

• R or RStudio installed on your system.


5. Introduction and Theory:

R provides special symbols for handling missing or undefined values and infinite quantities:

• NA (Not Available): Represents missing or undefined data. Any operation with NA results in NA.
• Inf: Represents positive infinity, typically resulting from division by zero.
• -Inf: Represents negative infinity, also resulting from division by zero with a negative numerator.

6. Operating Steps:

Step 1: Create an R Script

1. Open your preferred text editor or RStudio and create a new script file (NA_Inf_demo.R).

Step 2: Write the Script


Step 3: Run the Script

1. Save the script file.


2. Run the script in R or RStudio console.

7. Precautions:

• Be cautious when performing arithmetic operations involving NA, Inf, and -Inf.
• Use functions like [Link]() and [Link]() to handle such values effectively.

8. Observations:

• Any operation with NA results in NA.


• Division by zero yields Inf or -Inf based on the numerator's sign.
• Arithmetic operations involving Inf or -Inf behave as expected in mathematical terms, except in
ambiguous cases like Inf + (-Inf), which results in NaN.

9. Results and Interpretation:

The script successfully demonstrates how R handles NA, Inf, and -Inf in various calculations and how to
check for their presence.

10. Follow-Up Questions:


1. What happens when you multiply Inf by 0 in R?
2. How can you replace all NA values in a dataset with a default value?

11. Extension and Follow-Up Activities:

1. Create a function that identifies and replaces all NA, Inf, and -Inf values in a dataset.
2. Demonstrate the use of NaN (Not a Number) in R and its significance.

12. Assessments:

• Verify the output for calculations involving NA, Inf, and -Inf.
• Test the script for unexpected inputs or edge cases.

13. Suggested Readings

• R [Link]() Function Documentation


• R [Link]() Function Documentation

Experiment4:

1. Aim:

To write an R script that demonstrates the use of NA, Inf, and -Inf in calculations and explains their
significance.

2. Learning Outcomes:

• Understand the behavior of NA, Inf, and -Inf in calculations.


• Learn how R handles missing and infinite values during computations.

3. Prerequisites:

• Knowledge of basic arithmetic operations in R.


• Understanding of missing values (NA) and special numerical values (Inf, -Inf).

4. Materials:
• R or RStudio installed on your system.

5. Introduction and Theory:

R provides special symbols for handling missing or undefined values and infinite quantities:

• NA (Not Available): Represents missing or undefined data. Any operation with NA results in NA.
• Inf: Represents positive infinity, typically resulting from division by zero.
• -Inf: Represents negative infinity, also resulting from division by zero with a negative numerator.

6. Operating Steps:

Step 1: Create an R Script

1. Open your preferred text editor or RStudio and create a new script file (NA_Inf_demo.R).

Step 2: Write the Script


Step 3: Run the Script

1. Save the script file.


2. Run the script in R or RStudio console.

7. Precautions:

• Be cautious when performing arithmetic operations involving NA, Inf, and -Inf.
• Use functions like [Link]() and [Link]() to handle such values effectively

8. Observations:

• Any operation with NA results in NA.


• Division by zero yields Inf or -Inf based on the numerator's sign.
• Arithmetic operations involving Inf or -Inf behave as expected in mathematical terms, except in
ambiguous cases like Inf + (-Inf), which results in NaN.

9. Results and Interpretation:

The script successfully demonstrates how R handles NA, Inf, and -Inf in various calculations and how to
check for their presence.
10. Follow-Up Questions:

1. What happens when you multiply Inf by 0 in R?


2. How can you replace all NA values in a dataset with a default value?

11. Extension and Follow-Up Activities:

1. Create a function that identifies and replaces all NA, Inf, and -Inf values in a dataset.
2. Demonstrate the use of NaN (Not a Number) in R and its significance.

12. Assessments:

• Verify the output for calculations involving NA, Inf, and -Inf.
• Test the script for unexpected inputs or edge cases.

13. Suggested Readings:

• R [Link]() Function Documentation


• R [Link]() Function Documentation

Experiment5.

1. Aim:

To write an R script that:

1. Creates a 3x3 matrix with numbers from 1 to 9 and performs:


o Transpose of the matrix.
o Row-wise and column-wise sums.
2. Creates a 2x2x3 array with numbers from 1 to 12, assigns names to rows, columns, and dimensions, and
accesses specific elements.

2. Learning Outcomes:

• Understand matrix creation and basic operations like transpose and sums.
• Learn to create multi-dimensional arrays and assign names to dimensions.
• Access specific elements of arrays using indices.
3. Prerequisites:

• Knowledge of matrices and arrays in R.

4. Materials:

• R or RStudio installed on your system.

5. Script and Explanation:

Step 1: Matrix Operations

6. Output Example:

7. Precautions:

• Ensure correct dimensions when creating the matrix and array.


• Use appropriate indexing for accessing array elements.

8. Observations:

• The matrix transpose swaps rows and columns.


• Row and column sums are calculated independently.
• Array elements can be accessed by specifying row, column, and dimension names.

9. Results and Interpretation:

The program successfully demonstrates:

1. Matrix creation and operations like transpose and sums.


2. Array creation, dimension naming, and specific element access.
10. Follow-Up Questions:

1. What are the differences between matrices and arrays in R?


2. How can you reshape a matrix into an array or vice versa?

Experiment6:

1. Aim:

To demonstrate the use of:

1. Different assignment operators for assigning values to variables (a, b, c).


2. Arithmetic, relational, logical, and miscellaneous operators in R.

2. Learning Outcomes:

• Understand the usage of various assignment operators in R.


• Explore how arithmetic, relational, logical, and miscellaneous operators function in R programming.

3. Prerequisites:

• Basic understanding of variables and data types in R.

4. Concepts Covered:

1. Assignment Operators:

• =: Assigns values to variables.


• <-: Commonly used for assignment in R.
• ->: Assigns values from left to right.

2. Arithmetic Operators:

• Addition (+): Adds two numbers.


• Subtraction (-): Subtracts the second number from the first.
• Multiplication (*): Multiplies two numbers.
• Division (/): Divides the first number by the second.
• Exponentiation (^): Raises the first number to the power of the second.
• Modulo (%%): Gives the remainder of the division.
• Integer Division (%/%): Returns the integer part of the division.

3. Relational Operators:

• Greater than (>): Checks if the left operand is greater.


• Less than (<): Checks if the left operand is smaller.
• Equal to (==): Checks if both operands are equal.
• Not equal to (!=): Checks if operands are not equal.
• Greater than or equal to (>=): Checks if the left operand is greater or equal.
• Less than or equal to (<=): Checks if the left operand is smaller or equal.

4. Logical Operators:

• AND (&): Returns TRUE if both conditions are TRUE.


• OR (|): Returns TRUE if at least one condition is TRUE.
• NOT (!): Negates a logical condition.

5. Miscellaneous Operators:

• Sequence Operator (:): Creates a sequence of numbers.


• Membership Operator (%in%): Checks if an element belongs to a vector.
• Matrix Multiplication (%*%): Performs matrix multiplication.

5. Learning Observations:

• Assignment operators allow flexible ways to assign values.


• Arithmetic operators perform basic mathematical computations.
• Relational operators return boolean results based on comparisons.
• Logical operators are useful for combining or negating conditions.
• Miscellaneous operators extend functionality for specific use cases like sequences, memberships, or
matrix operations.

6. Applications:

• Use assignment operators for efficient variable management in R scripts.


• Apply arithmetic and relational operators for numerical computations and data analysis.
• Use logical operators for decision-making in conditional statements.
• Leverage miscellaneous operators for advanced tasks like generating sequences or performing matrix
operations.
7. Follow-Up Questions:

1. What are the differences between = and <- in R?


2. How do logical operators behave with vectors in R?
3. Explain the significance of %in% and provide practical use cases.

Experiment7:

1. Aim:

To implement control structures in R, including if-else, for, while, and repeat loops, along with
break and next statements.

2. Learning Outcomes:

• Understand the syntax and functionality of various control structures in R.


• Learn how to make decisions using if-else statements.
• Use loops (for, while, and repeat) effectively for iterative tasks.
• Explore the significance of break and next statements in controlling loop behavior.

3. Prerequisites:

• Familiarity with basic R programming.


• Understanding of looping and decision-making concepts.

4. Concepts Covered:

1. if-else Statement:

• Used for decision-making. Executes a block of code based on a condition.

2. for Loop:

• Used to iterate over a sequence (e.g., vectors, lists).

3. while Loop:

• Repeats a block of code while a specified condition is TRUE.


4. repeat Loop:

• Executes a block of code indefinitely until a break statement is encountered.

5. break Statement:

• Terminates a loop prematurely.

6. next Statement:

• Skips the current iteration of the loop and moves to the next iteration.

Introduction to Control Structures in R

In R programming, control structures are used to control the flow of execution based on certain
conditions or to repeat tasks. These structures allow you to automate decision-making and repetitive
tasks, making your programs more efficient and flexible.

Control structures in R can be divided into the following types:

1. Decision-making with if-else:


The if-else statement enables the program to choose one block of code to execute based on
whether a condition is true or false. It is the basic form of decision-making, allowing you to
handle different cases or conditions.
2. Repetition with Loops:
o for Loop: Used for iterating over a sequence, such as vectors or lists. It executes a block of code a
specific number of times.
o while Loop: Repeats a block of code as long as a specified condition is TRUE. This type of loop is
ideal when the number of iterations is not predetermined.
o repeat Loop: Continuously executes a block of code without a predetermined number of
iterations, until explicitly broken out using the break statement.
3. Controlling Loop Behavior:
o break Statement: Exits a loop immediately when a condition is met, regardless of the remaining
iterations. It provides a way to stop a loop prematurely.
o next Statement: Skips the current iteration of a loop and moves to the next one. This is useful
when certain conditions must be ignored during loop execution.

Control structures are fundamental to programming, allowing you to automate tasks, make your programs
more dynamic, and handle complex scenarios in a structured manner.

5. Program Description:

1. Check if a number is positive, negative, or zero:


o Use an if-else statement to check the entered number and print the appropriate message.
2. Print the first 10 natural numbers using a for loop:
o Use a for loop to iterate from 1 to 10 and print each number.
3. Calculate the factorial of a given number using a while loop:
o Continuously multiply the decreasing value of the number until it reaches 1.
4. Demonstrate break and next statements in a repeat loop:
o Use break to terminate the loop when a condition is met.
o Use next to skip specific iterations based on a condition.

6. Learning Observations:

• The if-else structure is essential for branching logic in programs.


• Loops (for, while, repeat) allow iterative operations with flexibility in control.
• break is helpful for exiting loops when a specific condition is satisfied.
• next enables skipping unnecessary iterations and improving efficiency.

7. Applications:

• Use if-else for data validation or conditional processing.


• Apply for and while loops for repetitive tasks like data manipulation, computation, or simulations.
• Leverage break and next for fine-grained control in complex looping scenarios.

8. Follow-Up Questions:

1. How does the behavior of a repeat loop differ from for and while loops?
2. Can you nest one type of loop inside another? Provide examples.
3. Why might you prefer break and next over adding conditions directly in loops?

Experiment8:

Aim:

The aim of this exercise is to demonstrate basic vector and string manipulation operations in R, including
vector creation, statistical calculations, sequence generation, and string manipulation functions.

Learning Outcomes:

• Understand how to create and manipulate vectors in R.


• Perform basic statistical operations on vectors (e.g., calculating mean, sum, min, and max).
• Learn how to generate sequences using seq() function.
• Concatenate and manipulate strings using R functions like paste(), substr(), and strsplit().
• Convert string case using toupper() and tolower() functions.

Prerequisites:

• Basic understanding of R programming concepts, including variables, functions, and vectors.


• Familiarity with the R programming environment and how to run scripts.

Materials:

• R software installed (RStudio or any preferred IDE).


• Access to the internet (optional, for additional reading or packages).

Introduction and Theory:

In R, vectors are one of the fundamental data structures that allow you to store multiple values of the
same type. They are essential when working with data sets, as they enable the storage and manipulation of
numbers, characters, or logical values in a single object.

String manipulation is equally crucial when dealing with textual data. R provides built-in functions to
manipulate strings, such as extracting substrings, splitting strings into words, and converting the case of
strings.

The mean(), sum(), min(), and max() functions are used for basic statistical operations, while the seq()
function generates sequences based on specified start, end, and step values. The paste() function is used
to concatenate elements into a single string.

In this exercise, you will explore vector and string manipulation techniques that are commonly used in
data processing and analysis.

Operating:

1. Create a numeric vector from 1 to 10.


2. Perform basic statistical operations using mean(), sum(), min(), and max().
3. Generate a sequence from 5 to 50 with a step of 5 using the seq() function.
4. Concatenate the vector elements into a single string using the paste() function.
5. Create a string manipulation script with the text "Brainware University" to demonstrate string operations.

Precautions:

• Ensure that the vector elements are numeric to use mathematical functions like mean() and sum().
• When using string manipulation functions, check if the text to be manipulated is correctly assigned to a
variable.
• Understand the syntax of the functions before using them to avoid errors.

Observations:
• The vector operations return the expected statistical values (e.g., mean, sum).
• The sequence generated by seq() should reflect the specified step.
• The paste() function concatenates elements correctly.
• String manipulation operations such as substr(), strsplit(), toupper(), and tolower() should
work as intended on the string "Brainware University".

Calculations:

1. For the vector from 1 to 10:


o mean() = (1 + 2 + 3 + ... + 10) / 10
o sum() = 1 + 2 + 3 + ... + 10
o min() = 1
o max() = 10
2. For the sequence from 5 to 50 with step 5, the output will be:
o 5, 10, 15, ..., 50.
3. For string manipulation:
o Extract "Brainware" from "Brainware University".
o Split the string "Brainware University" into individual words.
o Convert "Brainware University" to uppercase and lowercase.

Results and Interpretation:

• The statistical calculations on the vector will show the expected values for mean(), sum(), min(), and
max().
• The sequence will generate values from 5 to 50 in increments of 5.
• The string manipulations will show the extracted word, the split string, and the converted cases.

Follow-up Questions:

1. How can you modify the vector operations to work with larger datasets or different data types (e.g.,
characters or logical values)?
2. How would you handle missing values (NA) in a vector during statistical operations?
3. How can you apply string manipulation functions to process text data from a CSV file?

Extension and Follow-up Activities:

1. Create a more complex vector with random numbers and perform similar statistical operations.
2. Experiment with additional string manipulation functions like gsub() for pattern matching or
substring() for extracting custom parts of a string.
3. Apply similar string and vector manipulation to a larger dataset or text data file.

Assessments:

• Create a script that generates a vector with random numbers between 1 and 100, calculates the statistical
values, and generates a sequence.
• Write a script that manipulates a string containing a sentence or phrase, including extracting substrings
and modifying the case.

Suggested Readings:
1. R for Data Science by Hadley Wickham and Garrett Grolemund – A great resource for learning about data
manipulation and statistical analysis in R.
2. The Art of R Programming by Norman Matloff – Covers in-depth programming techniques, including
working with vectors and strings in R.
3. R Documentation:
o Vector Basics
o String Functions in R

Experiment9:

Aim:

The aim of this exercise is to demonstrate how to create and manipulate lists and matrices in R. It covers
tasks such as list creation, element addition and removal, list conversion, merging lists, and performing
matrix operations like addition, multiplication, and sum calculations.

Learning Outcomes:

• Create and manipulate lists in R, including adding, removing, and modifying elements.
• Convert a list into a vector and merge two lists.
• Perform basic matrix operations such as addition and multiplication.
• Access matrix elements and calculate row-wise and column-wise sums.

Prerequisites:

• Basic understanding of R programming concepts, including variables, functions, and data types like vectors
and lists.
• Familiarity with matrices and matrix operations.
• Knowledge of basic functions in R (e.g., sum(), matrix(), c()).

Materials:

• R software installed (RStudio or any preferred IDE).


• Access to the internet (optional, for additional reading or packages).

Introduction and Theory:

In R, lists are versatile data structures that can store different types of data, such as numbers, strings, and
vectors. Lists are an essential tool when dealing with heterogeneous data types, and you can add, remove,
or modify elements easily.

Matrices in R are two-dimensional arrays used to store data. They are widely used in numerical and
matrix operations, such as addition, multiplication, and accessing specific elements.

The matrix() function is used to create matrices, and operations like matrix addition, matrix
multiplication, and row-wise/column-wise sums are common tasks performed on matrices.
In this exercise, you will create a list to store multiple data types (name, age, and grades), add and remove
elements from the list, convert the list into a vector, merge two lists, and perform matrix operations.

Operating:

1. Create a list containing:


o Your name (character), age (numeric), and grades (numeric vector).
2. Add an element to the list (e.g., "Hobby").
3. Remove the age element from the list.
4. Convert the list into a vector and display the result.
5. Merge the two lists into a single list.
6. Create a 3x3 matrix with values from 1 to 9.
7. Perform matrix addition and multiplication with another 3x3 matrix of the same dimensions.
8. Access the element in the second row, third column of the matrix.
9. Calculate the row-wise and column-wise sums of the matrix.

Precautions:

• Ensure the correct data types are used when creating the list (e.g., characters for the name, numeric for
age and grades).
• When performing matrix operations, both matrices should have the same dimensions for addition and
multiplication to work.
• Be cautious when accessing matrix elements to avoid indexing errors.

Observations:

• The list will successfully store various types of data (string, numeric, and vector).
• Adding an element to the list and removing one will modify the list as expected.
• The list will be converted into a vector, displaying the combined elements.
• Matrix operations like addition and multiplication will result in a new matrix, and the sums will be
computed as specified.
• Accessing matrix elements will return the correct value.

Calculations:

1. Matrix creation (3x3):


o A matrix is created using the matrix() function with values from 1 to 9 arranged in 3 rows and 3
columns.
2. Matrix addition and multiplication:
o Addition: Adding the two matrices element-wise.
o Multiplication: Matrix multiplication will be carried out using %*%.
3. Row-wise and column-wise sums:
o Use apply() function to calculate sums:
▪ Row sums: apply(matrix, 1, sum)
▪ Column sums: apply(matrix, 2, sum)

Results and Interpretation:


• The list should contain the name, age, and grades after adding, removing, and converting elements.
• After merging two lists, the combined list will include all elements from both lists.
• Matrix operations will return the sum of corresponding elements for addition, and the result of matrix
multiplication will be displayed.
• The row and column sums will provide insight into the total sum across rows and columns in the matrix.

Follow-up Questions:

1. How can you handle a list with mixed data types when performing operations like addition or removal?
2. What happens if the two matrices involved in addition or multiplication have different dimensions?
3. How would you calculate row-wise and column-wise means instead of sums?

Extension and Follow-up Activities:

1. Modify the matrix to include random values and perform similar matrix operations (addition,
multiplication).
2. Create more complex lists (e.g., nested lists) and perform operations like sorting or subsetting.
3. Apply matrix operations to a real-world dataset (e.g., performing matrix multiplication on data stored in a
CSV file).

Assessments:

• Write a script to create a list with your details (name, age, grades) and perform operations like adding,
removing, and merging elements.
• Create two matrices of your choice and perform addition, multiplication, and calculate the row/column
sums.

Suggested Readings:

1. R for Data Science by Hadley Wickham and Garrett Grolemund – Provides a solid foundation for working
with data structures, including lists and matrices.
2. The Art of R Programming by Norman Matloff – Explores programming with R, covering advanced
techniques for data manipulation and matrix operations.
3. R Documentation:
o List Operations
o Matrix Operations

Experiment10:

Aim:

The aim of this exercise is to demonstrate how to create and manipulate arrays and factors in R. It
includes creating a 3-dimensional array, performing element access and replacement, and working with
factors by creating and modifying them.

Learning Outcomes:

• Create a 2x3x2 array in R and name its rows and columns.


• Access specific elements in the array using indexing.
• Modify elements in an array based on conditions.
• Create and modify factors in R.
• Display the levels of a factor and modify its levels.

Prerequisites:

• Basic understanding of R programming concepts, including vectors, arrays, and factors.


• Familiarity with indexing and subsetting in R.
• Knowledge of basic R functions like array(), gl(), and levels().

Materials:

• R software installed (RStudio or any preferred IDE).


• Access to the internet (optional, for additional resources or learning).

Introduction and Theory:

Arrays in R are multi-dimensional data structures that allow you to store data in more than two
dimensions. A 3-dimensional array, for example, can represent data in terms of layers, rows, and
columns. Arrays are useful when handling data that has more than two dimensions, such as images, time-
series data, or multidimensional measurements.

The array() function in R is used to create arrays. You can name the dimensions (rows, columns) and
layers using the dimnames argument, which helps in making the array more readable and organized.

Factors in R are categorical variables that can take on a limited number of values, known as levels.
Factors are used to represent qualitative data, such as categories or groups. The factor() function is used
to create factors, and the gl() function generates factors with specified levels repeated a specified
number of times. You can modify factors by adding or changing their levels.

Operating:

1. Create a 2x3x2 array:


o Generate an array with dimensions 2 (rows), 3 (columns), and 2 (layers), using values from 1 to 12.
o Name the rows as "Row1", "Row2", and the columns as "Col1", "Col2", "Col3".
2. Access elements:
o Access the element in the first row and second column of the second layer.
3. Modify array elements:
o Replace all elements in the array that are greater than 6 with NA.
4. Create and manipulate factors:
o Create a factor using the vector c("Red", "Blue", "Green", "Red", "Blue").
o Display the levels of the factor.
o Generate a factor with 3 levels ("High", "Medium", "Low") repeated 4 times using gl().
o Modify the factor to include a new level "Very High".

Precautions:
• Ensure the correct dimensions are set when creating the array, as an incorrect number of elements may
cause errors.
• While accessing elements in a multidimensional array, verify the row, column, and layer indices to avoid
out-of-bounds errors.
• When modifying factors, ensure that new levels are added using the correct method to avoid
misinterpretation.

Observations:

• The array will contain values from 1 to 12, distributed across the layers, rows, and columns as specified.
• The element in the first row, second column of the second layer will be correctly accessed.
• Elements greater than 6 in the array will be replaced with NA as per the instruction.
• The factor created from the vector will have specific levels, and modifications to its levels will be reflected
correctly.
• The factor created using gl() will repeat the levels appropriately.

Calculations:

1. Array creation:
o The array will be created using values 1 to 12, arranged in a 2x3x2 structure.
2. Element access:
o To access an element, use the indexing format array[row, column, layer].
3. Array modification:
o Use a conditional statement to replace values greater than 6 with NA.
4. Factor creation:
o factor(c("Red", "Blue", "Green", "Red", "Blue")) will create a factor.
o gl(3, 4) will generate a factor with three levels, repeated four times.
o Modify the factor to add a new level "Very High".

Results and Interpretation:

• The array will show the structured data from 1 to 12, with the appropriate names for rows and columns.
• The element accessed in the second layer and the first row, second column will be returned successfully.
• The elements greater than 6 in the array will be replaced with NA, and the resulting array will show the
changes.
• The factor will initially have the levels "Red", "Blue", and "Green" and will be modified to include "Very
High" as an additional level.
• The generated factor using gl() will show repeated levels based on the specified frequency.

Follow-up Questions:

1. What happens when you try to access an element outside the array dimensions?
2. How would you handle factors with unordered levels, and why is it important in data analysis?
3. How would you extend the array to have more layers and access an element in the new layers?

Extension and Follow-up Activities:


1. Create a 3x3x3 array with random values and perform similar operations like accessing elements and
replacing values.
2. Use factors in a dataset for categorical analysis and explore how levels impact the analysis results.
3. Modify the factor creation by using more complex level names and repeating patterns.

Assessments:

• Write a script to create a multidimensional array and perform operations like element access,
modification, and level modification for factors.
• Create a factor with unordered levels and demonstrate how R handles these in statistical analysis.

Suggested Readings:

1. R for Data Science by Hadley Wickham and Garrett Grolemund – This book provides a comprehensive
understanding of R data structures, including arrays and factors.
2. The Art of R Programming by Norman Matloff – Focuses on programming and manipulating arrays and
factors in R.
3. R Documentation:
o Array Operations
o Factor Operations

Experiment11:

Aim: To write an R script that processes text and performs operations on nested lists, including data
extraction, modification, and analysis.

Learning Outcomes:

1. Understand text processing in R.


2. Perform text extraction, replacement, and vowel counting.
3. Work with nested lists and data frames in R.
4. Manipulate and extract specific data from complex data structures.
5. Apply logical operations to categorize data based on performance.

Prerequisites:

1. Basic knowledge of R programming.


2. Familiarity with strings and lists in R.
3. Understanding of data frames and factor variables.
Materials Required:

1. RStudio or any R IDE.


2. R installed on the system.
3. Sample dataset for testing.

Introduction and Theory: Text processing is an essential part of data analysis, involving operations like
extraction, replacement, and counting characters. R provides functions such as strsplit(), gsub(), and
gregexpr() to process text efficiently.

Nested lists in R allow hierarchical data organization. A nested list can contain data frames, vectors, and
factors, enabling structured data management.

Operating Procedure:

Text Processing Tasks:

1. Extract every second word from the sentence "R Programming is Fun and Challenging".
2. Count the number of vowels (a, e, i, o, u) in the string.
3. Replace "Challenging" with "Exciting".

Nested List Operations:

1. Create a nested list containing:


o A data frame with student names, marks, and grades.
o A vector with total marks.
o A list of factors indicating performance categories.
2. Modify the data frame inside the nested list by adding a new student entry.
3. Extract students with "Excellent" performance.

Precautions:

1. Ensure correct indexing while extracting words from a sentence.


2. Validate data before modifying the data frame.
3. Handle missing values appropriately while working with nested lists.

Observations:

• The extracted words from the given sentence.


• The count of vowels present in the string.
• The modified sentence after replacement.
• The structure and content of the nested list before and after modification.
• The students categorized as "Excellent" based on performance.

Calculation and Analysis:

1. Use string manipulation functions to process text.


2. Apply list indexing techniques to retrieve and modify nested data.
3. Use logical conditions to filter students with "Excellent" performance.

Result and Interpretation:

• Successfully extracted every second word from the sentence.


• Correctly counted vowels in the string.
• Replaced "Challenging" with "Exciting" in the text.
• Created, modified, and analyzed a nested list containing student data.
• Extracted students who performed exceptionally well.

Follow-up Questions:

1. How can you extract every third word from a sentence?


2. What function in R helps count occurrences of specific characters?
3. How can a new column be added to an existing data frame inside a list?
4. How do you convert a vector into a factor in R?
5. What are the advantages of using nested lists over simple data structures?

Assessments:

1. Modify the script to extract every third word from a sentence.


2. Count occurrences of consonants in the given text.
3. Create a nested list with additional attributes like attendance and remarks.
4. Implement a function to categorize students into four performance levels.
5. Write a script to sort the student data frame based on marks.

Suggested Readings:

1. "R for Data Science" by Hadley Wickham & Garrett Grolemund


2. "Text Mining with R" by Julia Silge & David Robinson
3. R Documentation on stringr and dplyr packages
4. Online tutorials on R data structures and list manipulations
5. RStudio Cheat Sheets for text and data handling

Experiment12:

Aim: To create and manipulate factors in R and work with multi-dimensional arrays by performing
indexing, naming, and summation operations.

Learning Outcomes:

1. Understand the concept of factors in R and their importance in categorical data handling.
2. Perform frequency analysis on factors.
3. Modify factors by dropping specific levels.
4. Create and manipulate multi-dimensional arrays in R.
5. Access specific elements and compute the sum of all elements in an array.

Prerequisites:

1. Basic understanding of R programming.


2. Familiarity with factors and their usage.
3. Knowledge of multi-dimensional arrays in R.

Materials Required:

1. RStudio or any R IDE.


2. R installed on the system.

Introduction and Theory: Factors in R are used for handling categorical data. They allow efficient
storage and analysis of repeated text values. The table() function is commonly used to compute
frequencies.

Multi-dimensional arrays in R store data in structured formats, allowing efficient access and
manipulation. Naming rows, columns, and dimensions enhances data readability and usability.

Operating Procedure:
Factor Operations:

1. Create a factor for fruit names c("Apple", "Banana", "Orange", "Apple", "Banana").
2. Compute and display the frequency of each fruit using the table() function.
3. Drop the level "Orange" and display the updated factor.

Array Operations:

1. Create a 2x3x2 array with values from 1 to 12.


2. Assign names to rows, columns, and dimensions.
3. Access a specific element (e.g., row 1, column 2, dimension 1).
4. Compute the sum of all elements in the array.

Precautions:

1. Ensure factors are correctly defined before performing operations.


2. Verify the impact of dropping levels in factors to prevent unintended data loss.
3. When accessing array elements, check for valid indices to avoid errors.

Observations:

• The frequency count of each fruit category.


• The modified factor after removing "Orange".
• The correctly named and structured array.
• The retrieved element from the specified location in the array.
• The computed sum of all elements in the array.

Calculation and Analysis:

1. Use table() to compute factor frequencies.


2. Apply droplevels() to remove unwanted factor levels.
3. Assign row, column, and dimension names using dimnames().
4. Use array indexing to retrieve specific elements.
5. Compute the sum using the sum() function.

Result and Interpretation:

• Successfully created a factor and computed its frequency distribution.


• Dropped a specified level from the factor and displayed the updated values.
• Created a structured 3D array with named dimensions.
• Retrieved a specified element correctly.
• Computed and verified the total sum of array elements.

Follow-up Questions:

1. How can you convert a factor back to a character vector?


2. What function is used to reorder factor levels in R?
3. How do you create a 3D array with non-numeric data?
4. What happens if you try to access an out-of-range array index?
5. How do you determine the dimensions of an existing array in R?

Assessments:

1. Modify the factor to include an additional fruit category and analyze the impact.
2. Write a script to sort the factor levels alphabetically.
3. Create a 3x3x3 array and compute row-wise and column-wise sums.
4. Implement a function to check if a specific element exists in an array.
5. Write a program to reshape an array into a matrix and verify its dimensions.

Suggested Readings:

1. "R for Data Science" by Hadley Wickham & Garrett Grolemund


2. R Documentation on factors and arrays
3. Online tutorials on categorical data analysis in R
4. RStudio Cheat Sheets for data structures and handling

Experiment13:

Aim: To create, manipulate, and analyze a data frame in R using various functions.

Learning Outcomes:

1. Understand the structure and properties of data frames in R.


2. Perform data frame operations such as accessing rows and columns.
3. Use built-in functions to analyze data frame attributes.
4. Interpret outputs from functions like dim(), nrow(), ncol(), str(), and summary().

Prerequisites:
1. Basic understanding of R programming.
2. Familiarity with data structures in R, particularly data frames.
3. Knowledge of functions used for data inspection and manipulation.

Materials Required:

1. RStudio or any R IDE.


2. R installed on the system.

Introduction and Theory: A data frame in R is a table-like structure where each column can have
different data types. It is widely used for data manipulation and analysis. Functions like dim(), nrow(),
and ncol() provide insights into the structure of data frames, while summary() offers a statistical
overview of the dataset.

Operating Procedure:

Data Frame Operations:

1. Create a data frame with the following columns: Name, Age, and Marks.
2. Display the structure of the data frame using str().
3. Use dim(), nrow(), and ncol() to find its dimensions, number of rows, and columns.
4. View the first and last few rows using head() and tail().

Accessing Data:

1. Create another data frame with columns: Name, Age, and Score.
2. Display the newly created data frame.
3. Extract specific elements:
o All rows of the "Name" column.
o The first row of the data frame.
o The "Age" and "Score" columns for the first two rows.

Applying Functions:

1. Apply and interpret the output of the following functions on the data frame:
o dim()
o nrow()
o ncol()
o str()
o summary()
o names()
o head()
o tail()
Precautions:

1. Ensure correct column naming while creating data frames.


2. Verify data types using str() before performing operations.
3. Handle missing values appropriately if present.

Observations:

• The structure of the created data frame.


• The retrieved data from specific rows and columns.
• The outputs of various applied functions.

Calculation and Analysis:

1. Use str() to determine column data types.


2. Compute dimensions using dim().
3. Summarize the dataset with summary().
4. Extract relevant subsets using indexing.

Result and Interpretation:

• Successfully created and displayed a data frame.


• Retrieved specific rows and columns using indexing.
• Analyzed the structure and summary of the dataset.
• Used built-in functions to explore data frame properties.

Follow-up Questions:

1. How can you add a new column to an existing data frame?


2. What function is used to sort a data frame by a specific column?
3. How do you filter rows based on a condition?
4. What is the difference between summary() and str()?
5. How can you change column names in a data frame?

Assessments:
1. Modify the data frame to include an additional column, "Grade".
2. Write a script to filter students who scored above 80.
3. Implement a function to sort the data frame by the "Age" column.
4. Write a program to replace missing values in the data frame.
5. Create a new data frame with numeric columns and compute column-wise means.

Suggested Readings:

1. "R for Data Science" by Hadley Wickham & Garrett Grolemund


2. R Documentation on data frames
3. Online tutorials on data manipulation in R
4. RStudio Cheat Sheets for data handling

Experiment14:

Aim:

To understand and perform basic data frame manipulation techniques such as adding columns, adding
rows, combining data frames, and merging them using common columns.

Learning Outcomes:

By the end of this exercise, students will be able to:

• Add new columns to an existing data frame.


• Add new rows to an existing data frame.
• Combine two data frames with identical columns using a vertical stack.
• Add new columns to a data frame by horizontally combining data frames.
• Merge two data frames based on a common column.

Prerequisites:

• Basic knowledge of data frames in R.


• Familiarity with the concept of rows and columns in datasets.

Materials:

• Computer with R installed.


• A sample dataset (student information or similar).

Introduction and Theory:


In R, data frames are fundamental structures used to organize data. In this exercise, we will explore
various methods to modify, combine, and merge data frames. These operations are crucial for data
preprocessing, where data might come in different forms and need to be adjusted or combined.

1. Adding a New Column: This operation allows us to introduce new variables into an existing data frame,
which might be useful for adding labels, classifications, or derived metrics.
2. Adding a New Row: When we have more data to include in a dataset, we add new rows. This operation
increases the number of records in a data frame.
3. Combining Data Frames: This involves adding multiple data frames together either vertically (stacking
rows) or horizontally (adding columns).
4. Merging Data Frames: Similar to SQL joins, merging combines data from two data frames based on a
shared key, allowing for more comprehensive datasets.

Operating Procedure:

1. Add a New Column: Extend the data frame with a new attribute, like "Grade".
2. Add a New Row: Insert a new record (row) into the data frame with information about another student.
3. Combine Two Data Frames: Use rbind() to stack two data frames with identical columns on top of each
other.
4. Add a Column Using cbind(): Use this to add a new column, like "Hobbies", to an existing data frame.
5. Merge Two Data Frames: Use a common column, like "ID", to merge data frames from different sources,
combining them into a single, cohesive dataset.

Precautions:

• Ensure the data frames have matching structures before combining or merging them.
• When using cbind() to add columns, the number of rows in the new column must match the number of
rows in the original data frame.
• When merging, make sure the key column (e.g., "ID") exists in both data frames and has compatible data
types.

Observations:

• After adding a new column, the data frame will have an extra attribute for each record.
• When adding a new row, the data frame will grow by one more record.
• Merging will align records based on the common column, potentially expanding the number of columns if
they differ.

Calculation and Analysis:

• Analyze how the structure of the data frame changes after adding or removing data.
• Compare the original and merged data frames to observe how information from multiple sources has
been combined.

Result and Interpretation:

• After performing the operations, students should see how a data frame grows and how information can
be combined from various sources.
• The result of merging should include all data from both frames, aligned by the common key.

Follow-up Questions:

1. What challenges might arise when adding a column with missing values?
2. How would you deal with data frames having different column names when merging?
3. What is the difference between rbind() and cbind() in terms of their effects on data frames?

Assessments:

• Assess students' understanding of data manipulation by checking their ability to describe the operations
they performed.
• Evaluate their ability to explain what happens when different functions are used, such as rbind(),
cbind(), and merge().

Suggested Readings:

• R for Data Science by Hadley Wickham and Garrett Grolemund.


• The Art of R Programming by Norman Matloff.
• R documentation for rbind(), cbind(), and merge().

Experiment15:

To understand and perform data reshaping techniques in R using the melt() and dcast() functions,
converting data between long and wide formats.

Learning Outcomes:

By the end of this exercise, students will be able to:

• Reshape data from wide to long format using the melt() function.
• Convert reshaped data back from long to wide format using the dcast() function.
• Understand the concepts of wide and long formats and their applications.

Prerequisites:

• Basic understanding of data frames and their structure in R.


• Familiarity with the concepts of data reshaping and formats.

Materials:

• Computer with R installed.


• A sample dataset (could be a survey or sales data in a wide format).

Introduction and Theory:


Data reshaping is a process of converting a dataset between wide and long formats, which is essential for
various analyses. The two most common formats are:

• Wide format: Where each variable forms a separate column.


• Long format: Where each observation is split across multiple rows.

The melt() function from the reshape2 or [Link] package is used to convert data from wide to long
format. The dcast() function is used to convert data from long to wide format.

1. Melt: The melt() function takes a data frame in wide format and melts it into long format, where each
row corresponds to a single observation.
2. Dcast: The dcast() function is the inverse of melt(). It casts the long-format data back into a wide
format, essentially creating multiple columns for each variable based on the levels of the factor.

Operating Procedure:

1. Reshape Data with melt():


o Use the melt() function to reshape a wide-format data frame into long format. Each column of
the original data becomes a variable in the long format.
2. Reshape Data Back with dcast():
o After melting the data, use dcast() to reshape the long-format data back into wide format.

Precautions:

• When using melt(), ensure that the id variables (i.e., columns that remain constant across reshaped
data) are specified correctly.
• When using dcast(), ensure that the reshaped data has the correct grouping variables and measure
variables for the reshaping process to work properly.

Observations:

• After using melt(), the data frame will be reorganized such that multiple columns will be turned into
two: one for the variable name and one for the values.
• After using dcast(), the data will return to a wide format, where values are spread across multiple
columns.

Calculation and Analysis:

• Students can analyze the transformation by comparing the structures of the wide and long formats.
• Evaluate how the reshaping impacts the ability to perform certain types of analysis, such as aggregating
values or applying statistical models.

Result and Interpretation:

• After applying melt(), the data frame will be in a long format, which may be more suitable for certain
types of analyses, such as plotting or statistical modeling.
• After applying dcast(), the data will return to its wide format, allowing for easier comparison of
variables across different categories.
Follow-up Questions:

1. When might it be more appropriate to use the long format over the wide format, and vice versa?
2. What happens if you attempt to dcast() a dataset that has duplicate rows for the same identifier?
3. Can you use dcast() to perform calculations like sums or averages on reshaped data? How would you do
it?

Assessments:

• Evaluate students’ ability to describe the reshaping process and explain when and why they might use
long versus wide formats.
• Test students' ability to apply melt() and dcast() to reshape real-world datasets and interpret the
results.

Suggested Readings:

• R for Data Science by Hadley Wickham and Garrett Grolemund.


• Data Manipulation with R by Phil Spector.
• R documentation for the melt() and dcast() functions in the reshape2 or [Link] package.

Experiment:16

Aim:

To demonstrate how to check the current working directory, list files, save a data frame as a CSV file,
read it back into R, and perform basic summary statistics on the data.

Learning Outcomes:

By the end of this exercise, students will be able to:

• Check the current working directory using getwd().


• List all files in the current directory using dir().
• Save a data frame to a CSV file using [Link]().
• Read a CSV file back into R using [Link]().
• Analyze the data using summary statistics functions such as summary(), min(), max(), mean(), and
median().

Prerequisites:

• Basic understanding of R functions and data frames.


• Familiarity with file operations in R (reading/writing files).

Materials:

• Computer with R installed.


• A data frame (can be created or loaded from an existing dataset).

Introduction and Theory:

In R, it's essential to know how to manage your working environment, including checking the current
working directory, listing files, and saving and loading datasets. After saving a data frame to a CSV file,
you can read it back into R for further analysis. Summary statistics provide insights into the distribution
and central tendency of the data.

• getwd(): Returns the current working directory.


• dir(): Lists all files in the current working directory.
• [Link](): Saves an R data frame as a CSV file.
• [Link](): Reads a CSV file back into R.
• summary(): Provides a summary of the data, including minimum, maximum, mean, median, and
quartiles.
• min(), max(), mean(), median(): Functions for basic statistical analysis.

Operating Procedure:

1. Check Current Working Directory:


o Use getwd() to see where R is currently looking for files or saving them.
2. List All Files:
o Use dir() to list all the files in the current working directory.
3. Save Data Frame to CSV:
o Save the data frame as a CSV file using the [Link]() function.
4. Read CSV Back into R:
o Use [Link]() to read the saved CSV file back into R.
5. Analyze Data:
o Use summary(), min(), max(), mean(), and median() to analyze the data frame and obtain
key statistics.

Precautions:

• Ensure that the file path for saving and reading the CSV is correct and accessible.
• Make sure the data frame being analyzed contains numeric values for functions like min(), max(),
mean(), and median() to return meaningful results.

Observations:

• After using getwd(), the current directory will be displayed, which can help in understanding where files
are being saved or accessed from.
• The dir() function will list all files in the directory, including the saved CSV file.
• After saving and reading back the CSV, check if the data remains intact (i.e., no corruption during the
save/load process).
• Use summary functions to get a quick overview of the dataset’s properties.

Calculation and Analysis:


• The summary() function will provide the minimum, maximum, mean, and median values, as well as
quartiles for numeric columns.
• The min(), max(), mean(), and median() functions will give detailed information about the
distribution and central tendency of the numeric columns in the dataset.

Result and Interpretation:

• After reading the CSV file back into R, students should expect the data to be identical to the original data
frame.
• The summary statistics will help identify the spread and central tendency of the numeric data.

Follow-up Questions:

1. What happens if the CSV file contains non-numeric data? How does summary() handle it?
2. How would you handle missing values when analyzing the data (e.g., using [Link] = TRUE)?
3. What would happen if you attempted to read a CSV file with an incompatible structure (e.g., missing
headers)?

Assessments:

• Assess students’ understanding of basic file operations in R.


• Test their ability to perform basic summary statistics and interpret the results.
• Evaluate their ability to use functions like summary(), min(), max(), mean(), and median() to analyze
datasets.

Suggested Readings:

• R for Data Science by Hadley Wickham and Garrett Grolemund.


• R documentation for getwd(), dir(), [Link](), and [Link]().
• The Art of R Programming by Norman Matloff.

Experiment17:

Aim:

To perform basic mathematical operations, evaluate mathematical expressions, and compute statistics for
a given vector using R.

Learning Outcomes:

By the end of this exercise, students will be able to:

• Perform basic mathematical operations such as addition, subtraction, multiplication, and division.
• Compute mathematical functions like square roots, factorials, and exponentials.
• Evaluate trigonometric functions like sine, cosine, and tangent in both degrees and radians.
• Evaluate a mathematical expression for multiple values of xxx.
• Calculate basic statistics (sum, product, mean, median, standard deviation) for a vector.

Prerequisites:

• Basic understanding of arithmetic operations in R.


• Familiarity with mathematical functions in R.

Materials:

• Computer with R installed.


• A numeric vector or dataset for statistical calculations.

Introduction and Theory:

R provides a wide variety of built-in functions to perform mathematical operations and statistical
analyses. This exercise will cover basic arithmetic operations, advanced functions like square roots and
exponentials, and statistical functions for summarizing data.

1. Mathematical Operations: R supports basic arithmetic such as addition (+), subtraction (-), multiplication
(*), and division (/).
2. Mathematical Functions: R provides functions like sqrt() for square roots, factorial() for factorials,
and exp() for exponentials.
3. Trigonometric Functions: Functions like sin(), cos(), and tan() allow for the calculation of
trigonometric values, and R can handle both radians and degrees.
4. Evaluating Mathematical Expressions: You can evaluate expressions over a range of values using
vectorized operations.
5. Descriptive Statistics: Functions like sum(), prod(), mean(), median(), and sd() are used to
summarize data in a vector.

Operating Procedure:

1. Perform Mathematical Operations:


o a) For two numbers, use basic arithmetic operations like +, -, *, and /.
o b) Use sqrt(), factorial(), and exp() to calculate the square root, factorial, and exponential
of a number.
o c) Use sin(), cos(), and tan() for trigonometric functions in radians, and use deg2rad() to
convert degrees to radians before applying trigonometric functions.
2. Evaluate the Mathematical Expression:
o Use a for loop or vectorized operations to compute the expression 3x2+5x+2x2+1\frac{3x^2 + 5x +
2}{x^2 + 1}x2+13x2+5x+2 for x=1,2,…,10x = 1, 2, \dots, 10x=1,2,…,10.
3. Calculate Statistical Measures for a Vector:
o For a given vector, compute the sum and product using sum() and prod(), and calculate the
mean, median, and standard deviation using mean(), median(), and sd().

Precautions:

• Ensure that trigonometric functions are used with the correct angle unit (radians or degrees).
• Handle edge cases, like computing the factorial of large numbers (which can result in very large values).
Observations:

• The basic arithmetic operations should return numerical results directly.


• The mathematical functions will return values for square roots, factorials, and exponentials that depend
on the input values.
• Trigonometric functions will return values between -1 and 1 (or possibly undefined values in some cases).
• The evaluated expression should give a result for each value of xxx from 1 to 10.
• The statistical functions will return the desired summaries for the given vector.

Calculation and Analysis:

1. After performing the operations, observe how the values of the trigonometric functions vary with angle
and how the factorial grows rapidly with the input number.
2. For the expression 3x2+5x+2x2+1\frac{3x^2 + 5x + 2}{x^2 + 1}x2+13x2+5x+2, analyze how the results
change as xxx increases.
3. For the vector, check the spread (via standard deviation) and central tendency (via mean and median) of
the data.

Result and Interpretation:

• The basic arithmetic operations will yield simple results, while the more advanced functions will provide
insights into mathematical properties like growth rates (factorial) and curves (trigonometric functions).
• The evaluated expression will show how the mathematical formula behaves for a range of values.
• The vector's statistical properties will give an idea of the data's distribution and central tendency.

Follow-up Questions:

1. What is the impact of using radians versus degrees in trigonometric calculations?


2. How would the results change for larger values of xxx in the expression 3x2+5x+2x2+1\frac{3x^2 + 5x +
2}{x^2 + 1}x2+13x2+5x+2?
3. What happens if you try to calculate the factorial of a negative number in R?

Assessments:

• Assess students' understanding of basic mathematical functions in R.


• Evaluate their ability to perform vectorized operations and compute statistics on datasets.

Suggested Readings:

• R for Data Science by Hadley Wickham and Garrett Grolemund.


• The Art of R Programming by Norman Matloff.
• R documentation for basic mathematical functions like sqrt(), factorial(), exp(), and trigonometric
functions.

Experiment18:
Aim:

To create a dataset in R, calculate basic statistical measures for a numerical column, generate descriptive
statistics for the entire dataset, and visualize the data using a box plot to identify outliers.

Learning Outcomes:

By the end of this exercise, students will be able to:

• Create a dataset in R and calculate mean, median, mode, variance, standard deviation, and range for a
numerical column.
• Use the summary() function to generate descriptive statistics for an entire data frame.
• Create a box plot to visualize the distribution of a numerical column and identify potential outliers.

Prerequisites:

• Basic knowledge of R syntax and functions.


• Familiarity with statistical measures such as mean, median, mode, variance, and standard deviation.

Materials:

• Computer with R installed.


• A basic dataset (which will be created during this exercise).

Introduction and Theory:

R provides a variety of functions to compute descriptive statistics for a dataset. Descriptive statistics help
summarize the key features of the data, such as central tendency (mean, median, mode) and spread
(variance, standard deviation, range). Additionally, a box plot is a graphical representation of a dataset
that highlights the median, quartiles, and outliers.

1. Central Tendency:
o Mean: The average of the data.
o Median: The middle value of the data when sorted.
o Mode: The most frequent value in the data.
2. Spread:
o Variance: A measure of the dispersion of the data.
o Standard Deviation: The square root of the variance, providing a measure of how spread out the
data is.
o Range: The difference between the maximum and minimum values.
3. Box Plot: A box plot shows the distribution of a numerical column and highlights potential
outliers, which are values that lie outside the whiskers of the box.

Operating Procedure:

1. Create a Dataset:
o Use the [Link]() function to create a sample dataset with a numerical column.
2. Calculate Statistical Measures:
o Use mean(), median(), and a custom function for mode() to compute the central tendency
measures.
o Use var(), sd(), and range() to compute the spread measures.
3. Generate Descriptive Statistics:
o Use the summary() function to generate a summary for the entire data frame.
4. Create a Box Plot:
o Use the boxplot() function to create a box plot for a numerical column, which helps identify
potential outliers.

Precautions:

• Ensure that the data is numerical when calculating mean, median, and other statistical measures.
• Box plots may show extreme values as outliers, but it is essential to understand the context before
deciding whether they are truly outliers.

Observations:

• The box plot will show the central value (median), interquartile range (IQR), and potential outliers (values
outside the whiskers).
• The summary() function will give a quick overview of key statistics for each column in the data frame,
including minimum, maximum, mean, and quartiles.

Calculation and Analysis:

• Central tendency measures (mean, median, mode) will give insights into where most of the data is
centered.
• Spread measures (variance, standard deviation, range) will help assess the variability of the data.
• The box plot will visually represent the distribution of the data and identify any outliers.

Result and Interpretation:

• The mean(), median(), and mode() values should provide a central point around which the data tends
to concentrate.
• The variance(), sd(), and range() values will describe how spread out the data is.
• The box plot will show the distribution and any potential outliers, which may indicate errors or exceptional
cases.

Follow-up Questions:

1. How does the mean compare to the median in the presence of outliers?
2. What is the significance of the interquartile range (IQR) in identifying outliers?
3. How would you handle the outliers detected by the box plot in further analysis?

Assessments:

• Assess students’ ability to create a dataset in R and compute descriptive statistics.


• Evaluate their ability to interpret box plots and explain the presence of outliers.
• Test their understanding of the summary() function for generating quick statistics for a dataset.
Suggested Readings:

• R for Data Science by Hadley Wickham and Garrett Grolemund.


• R documentation for functions like mean(), median(), mode(), var(), sd(), range(), and
summary().
• The Art of R Programming by Norman Matloff.

Experiment19:

Aim:

To generate the frequency distribution of a categorical variable and create a histogram for a numerical
column to analyze the shape of the distribution (e.g., skewness, modality).

Learning Outcomes:

By the end of this exercise, students will be able to:

• Generate a frequency distribution for a categorical variable.


• Create a histogram to visualize the distribution of a numerical column.
• Analyze and interpret the shape of the histogram, including skewness and modality.

Prerequisites:

• Basic knowledge of R functions like table(), hist(), and plot().


• Understanding of statistical concepts like skewness, modality, and the importance of visualizing
distributions.

Materials:

• Computer with R installed.


• A dataset with both categorical and numerical columns.

Introduction and Theory:

1. Frequency Distribution:
o A frequency distribution is a table or chart that shows the number of occurrences (frequency) of
each category within a categorical variable.
o It helps to understand how data points are distributed across different categories.
2. Histogram:
o A histogram is a graphical representation of the distribution of a numerical variable.
o It divides the data into bins and shows the number of observations that fall within each bin.
o Key features of a histogram:
▪ Skewness: Refers to the asymmetry of the distribution. If the histogram tail is longer on
the right side, it is positively skewed, and if it is longer on the left side, it is negatively
skewed.
▪ Modality: Refers to the number of peaks (modes) in the histogram. A single peak
represents a unimodal distribution, while multiple peaks indicate a multimodal
distribution.

Operating Procedure:

1. Generate the Frequency Distribution:


o Use the table() function to calculate the frequency distribution for a categorical variable.
2. Create a Histogram:
o Use the hist() function to create a histogram for a numerical column in the dataset.
o Customize the histogram by adjusting the number of bins, colors, and labels.
3. Analyze the Shape of the Histogram:
o Evaluate whether the histogram is symmetric, skewed, or multimodal.
o Look for outliers or unusual patterns in the histogram.

Precautions:

• Ensure that the variable used for the frequency distribution is categorical.
• Make sure the numerical column for the histogram is continuous data (i.e., does not contain categories).

Observations:

• The frequency distribution will display how frequently each category appears in the categorical variable.
• The histogram will display the distribution of the numerical data. Key patterns to observe include:
o Skewness: Whether the distribution is more concentrated on the left or right.
o Modality: Whether the histogram has one or more peaks.

Calculation and Analysis:

• The frequency distribution will give insights into the proportions of each category in the dataset.
• The histogram will help assess whether the data is symmetrically distributed or skewed and whether there
are any clusters of data (modes).

Result and Interpretation:

• The frequency distribution will show the counts of each category, providing a snapshot of the categorical
variable.
• The histogram will allow interpretation of the overall distribution of the numerical variable:
o Skewness: If the histogram has a long tail on one side, it indicates skewness.
o Modality: If the histogram has one peak, it is unimodal, and if it has multiple peaks, it is
multimodal.

Follow-up Questions:

1. What is the effect of changing the number of bins in a histogram?


2. How does skewness affect the interpretation of a numerical variable?
3. What might be the cause of a multimodal distribution in a histogram?
Assessments:

• Assess students’ ability to generate a frequency distribution and interpret the results.
• Evaluate their ability to create and interpret histograms, particularly identifying skewness and modality.

Suggested Readings:

• R for Data Science by Hadley Wickham and Garrett Grolemund.


• R documentation for functions like table(), hist(), and summary().
• The Art of R Programming by Norman Matloff.

Common questions

Powered by AI

The array() function in R can create multi-dimensional structures by specifying the dimensions and values directly in the call, such as creating a 2x3x2 array with dim = c(2, 3, 2). Best practices include using descriptive names for dimensions using the dimnames argument to enhance readability and organization, aiding in managing and accessing data efficiently . Accurate dimension naming helps interpret analyses and data manipulations correctly, especially in complex datasets.

Using dcast() to reshape data from long to wide format in R enables easier direct comparison between variables and is ideal for data with clearly defined categories . Benefits include simplified visualizations and the ability to quickly observe inter-variable relationships. However, drawbacks include potential data duplication or loss of detail when categories are not unique, and increased complexity when re-integrating data into a single, comprehensive analysis . Correct formatting is crucial in contexts requiring variable transformations or aggregations.

Challenges in creating nested lists in R include maintaining consistent data types and structure within the hierarchy and managing memory usage effectively when dealing with large datasets . These challenges can be overcome by using consistent data type checks and validation functions to ensure lists elements conform to expected types, also employing efficient storage practices or leveraging R's object management capabilities to resolve memory concerns . It's crucial to document or visually map out the intended structure for clarity and maintainability.

Modifying factor levels in R is essential for accurate treatment of categorical data as it ensures levels are correctly represented in analysis, such as reordering them according to logical or custom criteria . Factors can be modified using functions like factor() or levels(). Ensuring that factors reflect a meaningful order or grouping can impact the results of statistical tests and visualizations by correctly representing relationships and hierarchies within data .

If matrices involved in operations like addition or multiplication do not share compatible dimensions, R will return an error, as these operations require that the matrices either have the same dimensions or meet specific criteria (e.g., inner dimensions for multiplication). In addition, element-wise operations assume parallel structures, thus dimension mismatch leads to unsuccessful operations .

To handle missing values, use the 'na.rm = TRUE' argument in functions like 'mean()' or 'sum()' to exclude them from calculations . When saving data frames to CSV, ensure missing values are marked explicitly (e.g., using 'NA') to maintain integrity across saving/loading cycles . Care should be taken to check file integrity post-loading by verifying that input and output data structures remain intact via functions like summary() or inspecting data with head() and tail().

Text processing functions like strsplit(), gsub(), and gregexpr() facilitate the manipulation and analysis of large text datasets by providing robust tools for string splitting, pattern matching, and replacement operations . These functions allow for efficient data cleaning, transformation, and preparation, enabling further tasks such as sentiment analysis, keyword extraction, and restructuring of text for analysis or visualization . They are essential in pre-processing stages to ensure text data conforms to analysis requirements.

Operations on lists containing mixed data types in R can lead to unexpected behaviors because R will attempt coercion into a common data type, which may not represent the original data correctly . Considerations include type consistency for operations intended to be numeric or character-specific and handling potential errors when the list is processed without prior checks for uniformity in data types . Special attention to operations that may trigger implicit type conversions or errors, such as arithmetic operations, is also necessary.

Basic mathematical operations in R, such as addition, subtraction, multiplication, and division, are performed using standard arithmetic operators . For evaluating complex expressions iteratively, control structures like loops or vectorized operations can be used to apply expressions across variable values, such as using a loop to evaluate (3x^2 + 5x + 2)/(x^2 + 1) for x = 1 to 10 . Efficient coding practices, like vectorization, enhance the performance of these computations significantly.

Using long format allows for more flexibility in statistical modeling as it simplifies the process of applying functions over groups or categories, making it suitable for analyses like repeated measures ANOVA or mixed-effects models . The wide format is easier for comparison across categories when the analysis context requires correlated comparisons between columns . Choosing between the formats depends on the specific statistical modeling requirements and the nature of the data.

You might also like