0% found this document useful (0 votes)
23 views26 pages

R Programming Practical Guide

Uploaded by

nain09364
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)
23 views26 pages

R Programming Practical Guide

Uploaded by

nain09364
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

Practical File

Of
R Programming
(24SEC0103P)

DEPARTMENT OF DATA SCIENCE & ARTIFICIAL INTELLIGENCE

Submitted To: Submitted By:


Mrs. Jyotsana Sardana Mam Komal
Assistant Professor Roll no. : 240252800022
(AI&DS) Dept. Class : [Link]. (AI&DS)

GURU JAMBHESHWAR UNIVERSITY OF


SCIENCE AND TECHNOLOGY
Hisar -- Haryana(India)
Sr. no. Programs Page no. Remark
1. Installing and Setup
A. Install and set up R and RStudio.
B. Familiarize yourself with the interface and various
windows
2. Create Objects in R
A. Create a vector of integers from 1 to 20.
3. Apply str() and summary() commands to the object.
A. str():
B. summary():
4. String Manipulation
A. Load the stringr library and analyze the string:
"apple, banana, cherry, date". Find and replace
"banana" with "blueberry".
5. Vector Operations
Create a vector of numbers from 1 to 200, divisible by 4.
Perform:
a) Calculate the length.
b) Extract the 10th, 25th, and 50th elements.
c) Replace values at index 15 with NA and find the mean
of the modified vector
6. Matrix Operations
Create a 3x3 matrix with random integers:
a) Replace elements at positions (2, 2) with NA.
b) Compute the column-wise mean.
7. String Operations
Analyze a vector of city names: c("New York",
"London", "Tokyo", "Paris", "Berlin").
a) Count characters in each name.
b) Find cities containing the letter "o".
8. Factor Data
Create a factor vector for vehicle types (Car, Bike, Bus,
Train):
a) Display factor levels.
b) Modify levels to include "Truck".
9. Employee Data Management
Create a data frame of 10 employees with names, age,
and monthly salaries. Find the employee with the highest
salary.
10. Histogram Plotting
Generate a histogram for the distribution of ages in a
dataset of 100 people.
11. Scatter Plot with Regression
Create a scatter plot for height vs. weight data and add a
regression line.
12. Data Frame Handling
Create a data frame of sales data (5 products, sales,
profit). Find the most profitable product.
13. Matrix Operations with Custom Data
Perform transpose and inversion operations on a 4x4
matrix.
14. Advanced Visualization
Plot the pressure dataset with different forms (line chart,
bar chart).
15. Create a matrix m of five rows in a row -major order of
numbers from 1 to 100 incremented by a step of 5 units:
a) Find row and columns -wise means of matrix m.
b) Find the minimum value for each row and column.
c) Find the transpose and sort the values in each columns
in decreasing order.
d) Assign the row names as R1to R5 and column names
C1 to C4.
e) Display all the elements of the second and fourth
column without using indices.
f) Display all the elements of the first and third row
without using indices.
g) Create a new matrix by deleting the second and fourth
column of matrix m using indices and column names.
h) Replace elements at indices (2,3), (2,4), (3,3), and
(3,4) with NA values.
i) Replace elements at index (1,3) with NaN.
j) Check if matrix m contains any NA or NaN values and
interpret the output.
k) Create two new matrices rm and cm by concatenating
matrix m row-wise and column-wise with itself.
16. Create a 4*3 matrix A of uniformly distributed random
integer numbers between 1 to 100. Create another 3*4
matrix B with uniformly distributed random integer
numbers between 1 to 10. Perform matrix multiplication
of the two matrices and store the result in a third matrix
C.
Project 1 : Install R and then install R Studio. Get yourself acquainted with
the GUI of various working windows of RStudio.
A Install and set up R and RStudio

Step 1: Install R
Download R:

• Visit the CRAN website.


[Link]
• Choose your operating system (Windows, macOS, or Linux).
• Download and run the installer.

Install R:

• Follow the on-screen instructions to complete the installation.

Step 2: Install RStudio


Download RStudio:

• Visit the RStudio website.


[Link]
• Choose the free version of RStudio Desktop and download the installer for your
operating system.

Install RStudio:

• Run the installer and follow the on-screen instructions.

Step 3: Open RStudio


• Launch RStudio after installation. It will detect your R installation automatically.
B. Familiarize yourself with the interface and various windows

Getting Acquainted with RStudio's GUI


The RStudio interface is divided into four main panes, each designed for specific tasks.

1. Source/Editor Pane (Top-Left)


• Purpose: For writing and editing R scripts, markdown files, and other documents.

• Features:

o You can save your code in files (.R, .Rmd) and execute them in parts.
o Syntax highlighting makes the code easier to read.

2. Console Pane (Bottom-Left)


• Purpose: Where you run R commands directly.
• Features:
o Type commands, and see immediate output.
o Errors or warnings will appear here.

3. Environment/History Pane (Top-Right)


• Environment Tab:
o Lists all objects (variables, data frames, functions) currently in memory.
o Use this to monitor your workspace.
• History Tab:
o Tracks the history of commands you have executed.
o Allows you to reuse commands without retyping.

4. Files/Plots/Packages/Help/Viewer Pane (Bottom-Right)


• Files Tab: Manage files in your working directory.
• Plots Tab: Displays visualizations and plots generated in R.
• Packages Tab: Install, load, or update R packages.
• Help Tab: Access documentation for R functions and packages.
• Viewer Tab: Used for rendering HTML reports, markdown documents, or web-
based content.
Project 2 : Create Objects in R
A. Create a vector of integers from 1 to 20.
Program:

Output:

B. Create a vector of factor type for different weather conditions (Sunny, Rainy, Cloudy,
Snowy).
Program:

Output:

C. Create a list of vectors with the names of 5 countries and their respective populations.
Program:

Output:

D. Create a data frame with 5 employees, their age, department, and monthly salary.
Program:
Output:
Project 3 : Apply str () and summary () commands to the object
A. Str ():
• The str () function gives a compact, structural summary of an object.

• It shows the data type, structure, and a quick overview of the components of
the object, such as the variable names and their data types.

Program:

Output:

B. Summary ():
• The summary () function provides a statistical summary of an object.

• For numeric data, it includes minimum, maximum, mean, median, and


quartiles.

• For factors, it shows the count of each level.

• For other data types, it provides relevant summaries

Program:

Output:
Project 4 : String Manipulation
A. Load the stringr library and analyze the string: "apple, banana, cherry, date".Find and replace
"banana" with "blueberry".
Program:

Output:
Project 5: Vector Operations
A. Create a vector of numbers from 1 to 200, divisible by 4. Perform:
a) Calculate the length.
b) Extract the 10th, 25th, and 50th elements.
c) Replace values at index 15 with NA and find the mean of the modified vector.

Program:

Output:
Project 6:Matrix Operations
A. Create a 3x3 matrix with random integers:
a) Replace elements at positions (2, 2) with NA.
b) Compute the column-wise mean.

Program:

Output:
Project 7: String Operations

A. Analyze a vector of city names: c("New York", "London", "Tokyo", "Paris", "Berlin").
a) Count characters in each name.
b) Find cities containing the letter "o".

Program:

Output:
Project 8: Factor Data

A. Create a factor vector for vehicle types (Car, Bike, Bus, Train):

a)Display factor levels.

b) Modify levels to include "Truck".

Program:

Output:
Project 9:Employee Data Management

A. Create a data frame of 10 employees with names, age, and monthly salaries. Find the
employee with the highest salary.

Program:

Output:
Project 10: Histogram Plotting

A. Generate a histogram for the distribution of ages in a dataset of 100 people.

Program:

Output:
Project 11 : Scatter Plot with Regression

A. Create a scatter plot for height vs. weight data and add a regression line.
Program:

Output:
Project 12 : Data Frame Handling

A. Create a data frame of sales data (5 products, sales, profit). Find the most profitable
product.

Program:

Output:
Project 13 : Matrix Operations with Custom Data.

A. Perform transpose and inversion operations on a 4x4 matrix.

Program:

Output:
Project 14 : Advanced Visualization.

A. Plot the pressure dataset with different forms (line chart, bar chart).

Program:

Output:
Project 15. Generating a Matrix with Row-Major Order of Numbers in R.

A. Create a matrix m of five rows in a row -major order of numbers from 1 to 100
incremented by a step of 5 units.
a) Find row and columns -wise means of matrix m.
b) Find the minimum value for each row and column.
c) Find the transpose and sort the values in each columns in decreasing order.
d) Assign the row names as R1to R5 and column names C1 to C4.
e) Display all the elements of the second and fourth column without using indices.
f) Display all the elements of the first and third row without using indices.
g) Create a new matrix by deleting the second and fourth column of matrix m using indices and
column names.
h) Replace elements at indices (2,3), (2,4), (3,3), and (3,4) with NA values.
i) Replace elements at index (1,3) with NaN.
j) Check if matrix m contains any NA or NaN values and interpret the output.
k) Create two new matrices rm and cm by concatenating matrix m row-wise and column-wise with
itself.

Program:
Output:
Project 16. Matrix Multiplication with Randomly Generated Matrices in R.

A. Create a 4*3 matrix A of uniformly distributed random integer numbers between 1


to 100. Create another 3*4 matrix B with uniformly distributed random integer
numbers between 1 to 10. Perform matrix multiplication of the two matrices and
store the result in a third matrix C.

Program:

Output:

Common questions

Powered by AI

To create a matrix with random integers in R, use the `matrix()` function combined with `sample()` for randomness. For a 3x3 matrix, populate it with random numbers. Elements can be modified using matrix indexing, e.g., setting m[2, 2] to NA. Column-wise means can be calculated using the `colMeans()` function, which handles NA by default, computing the mean of all available (non-NA) numbers in each column .

To generate a histogram in R for age distribution, use the `hist()` function with the dataset's age variable. Specify bins if necessary. Interpretation involves assessing the frequency density of ages: peaks indicate common age ranges, and spread showcases variability. Attention to features such as skewness or outliers provides comprehensive insights into the dataset’s age demographics .

Factors in R are used to represent categorical data. A factor vector is created using the `factor()` function which assigns levels to the categorical items. To modify levels, the `levels()` function is utilized. For example, after creating a factor vector for vehicle types, levels can be added or modified by assigning new levels directly, as when adding 'Truck' to existing levels ['Car', 'Bike', 'Bus', 'Train'].

The installation and setup of R and RStudio involve selecting the appropriate operating system on the CRAN website and downloading R, followed by installation via on-screen instructions. For RStudio, visit the RStudio website, download the free desktop version, and follow installation instructions. The RStudio interface is organized into four main panes: the Source/Editor Pane for writing and editing R scripts; the Console Pane to run R commands; the Environment/History Pane to manage objects and command history; and the Files/Plots/Packages/Help/Viewer Pane to manage files, visualize plots, manage packages, and access help documentation .

To analyze character vectors in R, `nchar()` counts the characters in each element. To identify names containing specific patterns, such as the letter 'o', use `grep()` for pattern matching. `grep()` returns indices of items matching the pattern, while `nchar()` provides length insights into individual strings .

The `str()` function in R provides a compact overview of an object's structure, detailing its data type and format. It is particularly useful for quickly understanding the composition of complex objects such as data frames or lists by showing the data type, number of observations, and variable names and types. This aids in ensuring data is structured as expected before further manipulation .

To transpose a matrix in R, use the `t()` function, which swaps rows and columns. Post-transposition, order each column in decreasing manner using `apply()` with `sort()`, setting the decreasing parameter to TRUE. This ensures each column, after the transpose, is sorted independently .

To identify and plot the most profitable product in a sales data frame, first calculate the profit for each product by assessing corresponding sales and profit data. Use basic operations to determine the maximum profit and its associated product. Visualization can be accomplished using `ggplot2` for a clear graphical representation. The function `ggplot()` can create bar plots to highlight the product with the most profit prominently .

String manipulation in R can be conducted using the 'stringr' library, which provides functions to handle strings. Specifically, for replacing an element in a string vector, functions like `str_replace()` can be used. For example, to replace 'banana' with 'blueberry' in the vector 'apple, banana, cherry, date', the `str_replace()` function from the 'stringr' library is employed .

Create a scatter plot in R using the `plot()` function, specifying variables for the x and y axes. To add a regression line, employ the `lm()` function to calculate the linear model and use `abline()` to overlay this model on the scatter plot, ensuring visual clarity of the regression relationship. These steps offer insights into the correlation between height and weight .

You might also like