R Programming Laboratory Manual
R Programming Laboratory Manual
Laboratory Manual
(Name of the Programme, Semester, Course and Code)
_____________________________________________________________________________________________
Table of Contents
Create a 2x2x3 array with numbers from 1 to 12, name its rows,
columns, and dimensions, and access specific elements.
6 19
10
Create a 2x3x2 array with values from 1 to 12.
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.
Create a 2x3x2 array with values from 1 to 12. Write a program to:
13
• dim()
• nrow()
• ncol()
• str()
• summary()
• names()
• head()
• tail()
• 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.
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.
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
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
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.
3. Result & Interpretation : The program demonstrates how R can perform basic arithmetic operations
effectively.
• 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 :
• 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:
3. Prerequisites:
4. Materials:
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:
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).
7. Precautions:
8. Observations:
9. Calculations:
The script successfully takes user input for name, age, and marks and displays it in a well-formatted
structure.
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:
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:
3. Prerequisites
4. Materials:
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:
1. Open your preferred text editor or RStudio and create a new script file (NA_Inf_demo.R).
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:
The script successfully demonstrates how R handles NA, Inf, and -Inf in various calculations and how to
check for their presence.
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.
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:
3. Prerequisites:
4. Materials:
• R or RStudio installed on your system.
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:
1. Open your preferred text editor or RStudio and create a new script file (NA_Inf_demo.R).
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:
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. 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.
Experiment5.
1. Aim:
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:
4. Materials:
6. Output Example:
7. Precautions:
8. Observations:
Experiment6:
1. Aim:
2. Learning Outcomes:
3. Prerequisites:
4. Concepts Covered:
1. Assignment Operators:
2. Arithmetic Operators:
3. Relational Operators:
4. Logical Operators:
5. Miscellaneous Operators:
5. Learning Observations:
6. Applications:
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:
3. Prerequisites:
4. Concepts Covered:
1. if-else Statement:
2. for Loop:
3. while Loop:
5. break Statement:
6. next Statement:
• Skips the current iteration of the loop and moves to the next iteration.
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 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:
6. Learning Observations:
7. Applications:
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:
Prerequisites:
Materials:
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:
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:
• 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?
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:
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:
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:
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?
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:
Prerequisites:
Materials:
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:
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".
• 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?
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:
Prerequisites:
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:
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".
Precautions:
Observations:
Follow-up Questions:
Assessments:
Suggested Readings:
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:
Materials Required:
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:
Precautions:
Observations:
Follow-up Questions:
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:
Experiment13:
Aim: To create, manipulate, and analyze a data frame in R using various functions.
Learning Outcomes:
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:
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:
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:
Observations:
Follow-up Questions:
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:
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:
Prerequisites:
Materials:
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.
• 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.
• 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:
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:
• 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:
Materials:
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:
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.
• 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.
• 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:
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:
Prerequisites:
Materials:
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.
Operating Procedure:
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.
• 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:
Suggested Readings:
Experiment17:
Aim:
To perform basic mathematical operations, evaluate mathematical expressions, and compute statistics for
a given vector using R.
Learning Outcomes:
• 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:
Materials:
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:
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:
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.
• 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:
Assessments:
Suggested Readings:
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:
• 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:
Materials:
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.
• 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.
• 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:
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:
Prerequisites:
Materials:
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:
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.
• 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).
• 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:
• 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:
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.