Module-1
STATISTICAL COMPUTING AND DATA
TRANSFORMATION
Dr. Sonali Mahure
Contents:
R Tool: Transform continuous variables to
Installing, loading and updating R categorical variables,
packages, Handling missing values,
Creating objects, Sub-setting data frames,
Data types, Data structures, Appending and merging data frames,
Sorting vectors and data frames, Split data frames,
Directory management commands, Stack and unstack data frames
Direct data entry in R(for small data sets),
Importing data from other software,
Decision structures (if, if-else, if-else if-
else),
Repetitive structures (for and while loops),
Other functions (break, next, warn, stop)
Data Wrangling and Cleaning:
Dr. Sonali Mahure
Installing R and R studio
RStudio is an open-source integrated development environment (IDE) for R.
It provides several features that enhance productivity and ease of use:
IDEfor R: Syntax highlighting, code completion, and debugging tools.
Project Management: Organizes scripts, data, and visualizations for better
workflow.
Data Visualization: Integrates with powerful plotting libraries like ggplot2.
Package Management: Easily install and manage R packages via CRAN.
R Markdown: Seamlessly create reports combining code, text, and graphics.
Collaboration: Supports Git and RStudio Server for project sharing and team work
Installing R and RStudio on Windows
To Install R and R Studio on Windows we will have to download R and R Studio with
the following steps.
First, you need to set up an R environment in your local machine. Visit the official
CRAN website: [Link]
Dr. Sonali Mahure
You have to download both the applications
first go with R Base and
then install RStudio. after click on install R you will get a new page like this.
Here we can select the linux, mac or windows any one according to users system.
you have to click on for which you want to install.
Dr. Sonali Mahure
now click on the link show above in image so R base starts downloading and after
that again go to main page and download and click on Install RStudio.
After downloading R for the Windows platform, install it by double-clicking it.
Step 2: Download R Studio from their official page. Note: It is free of cost (under AGPL
licensing).
Step 3: After downloading, you will get a file named "[Link]" in your
Downloads folder.
Step 4: Double-click the installer, and install the software.
Step 5: Search for RStudio in the Window search bar on Taskbar.
Dr. Sonali Mahure
Creation and Execution of R File in R Studio
Step 6: Your installation is successful.
1. Creating an R file
There are two ways to create an R file in R studio:
1. You can click on the File tab, from there when you click it will give a drop-down
menu, where you can select the new file and then R script, so that, you will get a
new file open.
2. Use the plus button, which is just below the file tab and you can choose R script,
from there, to open a new R script file.
2. Saving an R File
From the file menu if you click the file tab you can either SAVE or SAVE AS button.
When you want to save the file if you click the SAVE button, it will automatically save
the file has untitled x.
So, this x can be 1 or 2 depending upon how many R scripts you have already opened.
Dr. Sonali Mahure
3. Execution of an R file
There are several ways in which the execution of the commands that are available in the
R file is done.
Using the run command: This "run" command can be executed using the GUI, by
pressing the run button there, or you can use the Shortcut key ctrl + Enter. It will
execute the line in which the cursor is there.
Using the source command: This "source" command can be executed using the GUI,
by pressing the source button there, or you can use the Shortcut key control + shift +
S. It will execute the whole R file and only print the output which you wanted to print.
Using the source with echo command: This "source with echo" command can be
executed using the GUI, by pressing the source with echo button there, or you can use
the Shortcut key control + shift + enter. It will print the commands also, along with
the output you are printing.
x <- 10 y <- 20 print(x + y)
Dr. Sonali Mahure
Difference Between all the Execution Methods
Command Usage Advantages Disadvantages
Helps with
Populates the console,
Executes selected troubleshooting and
Run making it messy with
lines of R code. debugging specific parts
unnecessary output.
of the code.
Runs the entire script, Cannot selectively run
Executes the entire
Source ensuring all code is or debug specific lines,
R script file.
executed in order. executes everything.
May clutter the console
Runs the entire file Allows to see the code
Source with with code output,
and displays code as it’s executed, helpful
Echo especially for large
in the console. for debugging.
scripts.
Dr. Sonali Mahure
Variables in R
Dr. Sonali Mahure
Execution and assignment
In R, the assignment can be denoted in three ways:
1.= (Simple Assignment)
2.<- (Leftward Assignment)
3.-> (Rightward Assignment)
Comments in R
Single line comments can be written by using # at the beginning of the statement.
Dr. Sonali Mahure
if, else, repeat, while, function, for, in, next and break are used for control-flow
statements and declaring user-defined functions.
The ones left are used as constants like TRUE/FALSE are used as boolean constants.
NaN defines Not a Number value and NULL are used to define an Undefined value.
Inf is used for Infinity values.
---Prepare a list of all the operators
Dr. Sonali Mahure
R-Data Types
R Programming language has the following basic R-data types and the following table shows the
data type and the values that each data type can take.
Basic Data Types Values Examples x = 5.6
print(class(x))
Numeric Set of all real numbers "numeric_value <- 3.14" print(typeof(x))
Integer Set of all integers, Z "integer_value <- 42L"
y=5
Logical TRUE and FALSE "logical_value <- TRUE"
print(class(y))
Complex Set of complex numbers "complex_value <- 1 + 2i" print(typeof(y))
"a", "b", "c", ..., "@", "#", "$", ...., y=5
Character "character_value <- "Hello RProg"
"1", "2", ...etc print([Link](y))
raw [Link]() "single_raw <- [Link](255)"
When R stores a number in a variable, it converts the number into a "double" value or a decimal type with at least
two decimal places.
A value such as "5" here, is stored as 5.00 with a type of double and a class of numeric. y is not an integer here can be
confirmed with the [Link]() function.
we can use the capital 'L' notation as a suffix to denote that a particular value is of the integer R data type.
Dr. Sonali Mahure
Data Structures
1. Vectors
A vector is a sequence of data elements of the same data type.
All the elements of a vector must be of the homogeneous. marks <- c(80, 75, 90, 85)
We use the C() function to declare a vectors. print(marks)
Vectors are one-dimensional data structures.
print(length(marks))
print(sum(marks))
print(max(marks))
print(min(marks))
Dr. Sonali Mahure
2. Lists
A list can store different types of data together.
Lists are heterogeneous data structures.
These are also one-dimensional data structures.
To create a List in R you need to use the function called "list()".
A list can be a list of vectors, list of matrices, a list of characters and a list of functions
and so on.
student <- list(name="Ram", age=21, marks=c(70,80,90))
print(student)
print(student$name)
print(student$marks)
Dr. Sonali Mahure
3. Data Frames
A Data Frame is a 2-dimensional, heterogeneous table in R which are used to store the
tabular data.
It Has rows and columns
Data frame Can store different data types in different columns.
Very important in Data Analytics
student <- [Link](
Name = c("Amiya", "Raj", "Asish") name = c("Ram", "Sita", "Arun"),
Language = c("R", "Python", "Java") age = c(21, 22, 20),
Age = c(22, 25, 45) marks = c(85, 90, 88)
df = [Link](Name, Language, Age) Language = c("R", "Python", "Java")
print(df)
)
print(student)
Dr. Sonali Mahure
4. Matrices
A Matrices are two-dimensional, homogeneous data structures.
Has rows and columns
But all elements must be same data type
Only one data type allowed.
A = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3,ncol =
3,)
print(A)
Accessing element : A[1,2]
Dr. Sonali Mahure
5. Arrays
An Array is multi-dimensional data structure.
Array can be 2D, 3D, 4D etc
All elements must be same data type.
They are homogeneous data structures.
A = array( c(1, 2, 3, 4, 5, 6, 7, 8), dim = c(2, 2, 2) )
print(A)
Dr. Sonali Mahure
Practice questions
1. Create Variables and Print the variables and type of Variable
Output :
a <- 25
name <- "Rahul"
Pass <- TRUE
print(a)
print(typeof(a))
print(name)
print(typeof(name))
print(Pass)
print(typeof(Pass))
Dr. Sonali Mahure
Practice Question
2. Check Data Type
OutPut:
x <- 10.5
y <- "Hello"
z <- FALSE
print(class(x))
print(class(y))
print(class(z))
Dr. Sonali Mahure
Practice Question
3. Create a Vector and Perform Operations
Output
marks <- c(80, 75, 90, 85)
print(marks)
print(length(marks))
print(sum(marks))
print(max(marks))
print(min(marks))
Dr. Sonali Mahure
Practice Questions
4. Access Vector Elements
Output :
v <- c(10, 20, 30, 40)
print(v[1])
print(v[3])
Dr. Sonali Mahure
Practice Questions
5. Create a List
Output
student <- list(name="Ram", age=21,
marks=c(70,80,90))
print(student)
print(student$name)
print(student$marks)
Dr. Sonali Mahure
Practice Questions
6. Create a Matrix and access matrix elements
m <- matrix(c(1,2,3,4,5,6), nrow=2, ncol=3) Output :
print(m)
print(m[1,2])
Dr. Sonali Mahure
Practice Questions
7. Create an Array with 2 columns, 2 rows and 2 layers
Output :
arr <- array(1:8, dim=c(2,2,2))
print(arr)
OR
arr <- array(c(1, 2, 3, 4, 5, 6, 7, 8), dim=c(2,2,2))
print(arr)
Dr. Sonali Mahure
6. Factors
Factors are the data objects which are used to categorize the data and store it as
levels.
They are useful for storing categorical data.
They can store both strings and integers.
They are useful to categorize unique values in columns like (“TRUE” or “FALSE”) or
(“MALE” or “FEMALE”), etc..
gender <- c("Male", "Female", "Male", "Female","Trans-Gender")
print(gender)
gender_factor <- factor(gender)
print(gender_factor)
Dr. Sonali Mahure
7. Tibbles
Tibbles are an enhanced version of data frames in R, part of the tidyverse / dplyr
package..
They offer improved printing, stricter column types, and allow variables to be referred
to as objects.
Tibbles provide a modern, user-friendly approach to tabular data in R.
library(tibble)
[Link]("tibble") # only first time
library(tibble)
student <- tibble( Name = c("Ram", "Shyam",
"Sita"), Age = c(21, 22, 20), Marks = c(80, 75,
90))
print(student)
Dr. Sonali Mahure
Sorting vectors and data frames
Sorting vectors
The sort() function is used to sort a vector.
Ascending order (default) Descending order :
my_vector <- c(5, 3,1,2,4) my_vector <- c(5, 2, 8, 1, 9)
sorted_vector_desc <- sort(my_vector) sorted_vector_desc <- sort(my_vector, decreasing =
print(sorted_vector_desc) TRUE)
print(sorted_vector_desc )
Dr. Sonali Mahure
Sorting Data Frames:
order() function (increasing and decreasing order)
arrange() function from dplyr package
setorder() function from [Link] package
The order() function is commonly used to sort data frames, as sort() cannot directly
sort entire data frames.
Dr. Sonali Mahure
Sorting by a single column (ascending):
my_dataframe <- [Link]( Name = c( "Bob","Alice", "Charlie","Edge","Dwane"), Age
= c(30, 25, 35,44,50) )
print(my_dataframe)
sorted_df <- my_dataframe[order(my_dataframe$Name), ]
print(sorted_df)
Sorting by a single column (descending)
my_dataframe <- [Link]( Name = c("Alice", "Bob", "Charlie"), Age = c(30, 25, 35) )
sorted_df_desc <- my_dataframe [order(- my_dataframe$Age), ]
Print(sorted_df_desc) # - sign applies only for numeric values
Dr. Sonali Mahure
my_dataframe <- [Link]( Name = c("Alice", "Bob", "Charlie"), Age = c(30, 25, 35) )
sorted_df <- my_dataframe[order(my_dataframe$Name, decreasing = TRUE), ]
print(sorted_df)
Dr. Sonali Mahure
Sorting by multiple columns.
my_dataframe <- [Link](
Name = c("Alice", "Bob", "Charlie", "David"), Age = c(30, 25, 30, 35), Score = c(90, 85, 95, 80))
# Sort by 'Age' ascending, then by 'Score' descending for ties
sorted <- my_dataframe[order(my_dataframe$Age, -my_dataframe$Score), ]
Dr. Sonali Mahure
# Directory management commands, Direct data entry in R(for small
data sets),
Get Working directory:
getwd(): The getwd() method is used to gather information about the current
working pathname or default working directory. print(getwd())
print ("Current working directory")
getwd()
set up a working directory:
# set working directory to its parents directory
setwd("..")
print ("Modified working directory")
getwd()
Dr. Sonali Mahure
Importing data from other software
We can read external datasets and operate with them in our R environment by
importing data into an R script.
R programming language offers a number of functions for importing data from
various file formats.
For this demonstration, we will use two examples of a single dataset, one in .csv form
and another .txt
1a. Using [Link]() Function Read CSV Files into R
The function has two parameters:
[Link](): It opens a menu to choose a CSV file from the desktop.
header: It is to indicate whether the first row of the dataset is a variable name or
not. Apply T/True if the variable name is present else put F/False.
data1 <- [Link]([Link](), header=T)
Print(data1)
Dr. Sonali Mahure
Using File Path
data1 <- [Link]("C:/Users/vvina/Downloads/[Link]", header = TRUE)
print(data1)
b. Using [Link]() Function
This function specifies how the dataset is separated, in this case we take sep=", " as
an argument.
data2 <- [Link]([Link](), header=T, sep=", ")
data2
data4 <- [Link]([Link](), header=T, sep="\t")
data4
Dr. Sonali Mahure
2. Reading a Tab-Delimited(txt) File:
1. Using [Link]() Function
The function has two parameters:
[Link](): It opens a menu to choose a csv file from the desktop.
header: It is to indicate whether the first row of the dataset is a variable name or not.
Apply T/True if the variable name is present else put F/False.
data3 <- [Link]([Link](), header=T)
data3
Dr. Sonali Mahure
3. Using R-Studio
Here we are going to import data through R studio
with the following steps.
From the Environment tab click on the
Import Dataset Menu.
Dr. Sonali Mahure
Decision structures (if, if-else, if-else if-else),
Decision making in programming allows us to control the flow of execution based on
specific conditions. In R, various decision-making structures help us execute
statements conditionally. These include:
1. if statement
2. if-else statement
3. if-else-if ladder
4. nested if-else statement
5. switch statement
1. if Statement
The if statement evaluates a condition. If the condition is TRUE, the associated
statement is executed. If the condition is FALSE, the statement is skipped.
Dr. Sonali Mahure
x = 10 2. if-else Statement
if(x < 11){
The if-else statement executes one
print("X is lesser than 11") block if the condition is TRUE and
} another if it is FALSE.
y <- 100
if(y > 10){
print(paste(y, "is greater than 10"))
}
Dr. Sonali Mahure
# If else statements
# If else statements
num1<-1000
num2<-100
# Check value is less than or greater than
if(num1 > =num2){
print(paste(num1, "is greater than ",num2))
}else{
print(paste(num2, "is less than ",num1))
}
3. if-else-if Ladder
This structure chains multiple conditions together.
Each condition is evaluated in sequence. If a condition is TRUE,
its block is executed.
Otherwise, the next condition is checked.
Dr. Sonali Mahure
# Assign values
num1 <- 10
num2 <- 20
num3 <- 30
if (num1 >= num2 && num1 >= num3) {
print(paste(num1, "is the largest number"))
}
else if (num2 >= num1 && num2 >= num3) {
print(paste(num2, "is the largest number"))
}
else {
print(paste(num3, "is the largest number"))
}
Dr. Sonali Mahure
Repetitive structures (for and while loops),
1. For Loop in R
The for loop is used when we know the exact number of iterations required.
It iterates over a sequence such as a vector, list or numeric range.
Dr. Sonali Mahure
Vector List
zz=c(1,2,3,4,5) y<-list(1,2,3,4,5,6,7,8,9)
for(i in zz){ for(i in y){
print(i)} print(i)}
Array
A = array( c(1, 2, 3, 4, 5, 6, 7, "Eight"), dim = c(2, 2, 2) )
print(A)
for(i in A){
print(i)}
Dr. Sonali Mahure
For-Loop on a List
The seq_along() function is used to create a list of indices to loop through and
double brackets [[]] are used to retrieve the current element during each loop
iteration.
We print a message showing the element we're dealing with inside the loop followed
by the value of that element.
my_list <- list(5,4,2,3,1)
for (i in 1:length(my_list)) {
print(paste("Index:", i, "Value:", my_list[[i]]))
}
Dr. Sonali Mahure
2. While Loop in R
The while loop runs as long as a specified condition holds TRUE. It is useful when the
number of iterations is unknown beforehand.
x<-1
while(x<=5){
print(x)
x=x+1}
3. Repeat Loop in R
The repeat loop executes indefinitely until
explicitly stopped using the break statement y<-1
To terminate the repeat loop we use a jump repeat{
statement that is the break keyword print(y)
y=y+2
if(y>=1000){
break }
}
Dr. Sonali Mahure
Other functions (break, next, stop)
Next statement in R using For-loop
no <- 1:10
for (val in no)
{
if (val == 6)
{
next
}
print(paste("Values are: ", val))
}
Dr. Sonali Mahure
stop(...): It halts the evaluation of the current statement and generates a message
argument. The control is returned to the top level.
x <- -5
if (x < 0) {
stop("Error: x should not be negative")
}
print("Program continues")
Dr. Sonali Mahure
Practice questions for students
1. Create a vector of grades: "A", "B", "A", "C", "B", "A".
a) Convert it into a factor.
b) Display the levels.
Dr. Sonali Mahure
Practice questions for students
2. Create a tibble with columns:
Name
Age
Department
b) Display the structure of tibble.
Dr. Sonali Mahure
Practice questions for students
3. Given a numeric vector:
marks <- c(45, 88, 72, 90, 60)
a) Sort the vector in ascending order.
b) Sort the vector in descending order.
Dr. Sonali Mahure
Practice questions for students
4. Create a data frame with Name and Salary.
a) Sort the data frame based on Salary in ascending order.
b) Sort the data frame based on Salary in descending order.
c) Sort based on Name in decreasing alphabetical order.
Dr. Sonali Mahure
Practice questions for students
Write R commands to:
a) Import a CSV file using full file path.
b) Import a CSV file using [Link]().
c) Import a CSV file using RStudio Environment tab.
Dr. Sonali Mahure
Practice questions for students
6. Write a program to check whether a number is even or odd using if-else.
Dr. Sonali Mahure
Practice questions for students
7. Write a program to classify marks:
•Above 80 → Distinction
•60–79 → First Class
•40–59 → Pass
•Below 40 → Fail
Dr. Sonali Mahure
Practice questions for students
8. Write a program using for loop to:
a) Print numbers from 1 to 10.
b) Print only even numbers between 1 to 20.
Dr. Sonali Mahure
Practice questions for students
9.
a) Use while loop to print numbers from 1 to 5.
b) Use repeat loop to print numbers until value becomes 5 and then exit the loop using
break.
Dr. Sonali Mahure
Practice questions for students
10.
a) Write a program using for loop to print numbers from 1 to 10 but skip number 5
using next.
b) Write a program that stops execution if a number is negative using stop().
Dr. Sonali Mahure
Data Wrangling and Cleaning
Data Wrangling means:
Cleaning and transforming raw data so that it becomes useful for analysis.
Example:
Real data often has problems like:
• Missing values
• Duplicate data
• Wrong format
So we clean and organize the data before analysis.
Dr. Sonali Mahure
Transform continuous variables to categorical variables
What is a Continuous Variable?
A continuous variable is a variable that can take any numeric value within a range
Variable Example Values
Age 18, 21, 35
Height 165.5, 170.2
Marks 45, 78, 92
Salary 25000, 50000
Example: marks <- c(45, 67, 89, 72, 55)
Here marks are numbers, so this is a continuous variable.
Dr. Sonali Mahure
What is a Categorical Variable?
A categorical variable represents groups or categories instead of numbers.
Category Example Values
Gender Male, Female
Grade A, B, C
Status Pass, Fail
Department IT, HR, Sales
Example : grade <- c("A","B","C","B","A")
Here values represent categories, not measurements.
Dr. Sonali Mahure
Example: Transform Continuous to Categorical Variable
Example: marks <- c(85, 72, 40, 90, 65) # Continuous Variable
Convert Marks(Continuous) to Grade (Categorical)
2) Using cut() :
The cut() function is specifically designed to "bin" numeric data
into categories. It is usually the most efficient way to handle
1) Using If-else:
grading scales.
marks <- c(85,72,40,90,65)
marks <- c(85, 72, 40, 90, 65)
grade <- ifelse(marks >= 80,"A",
# Breaks define the ranges: 0-60 (C), 60-80 (B), 80-100 (A)
ifelse(marks >= 60,"B","C")) grade <- cut(marks,
[Link](marks, grade) breaks = c(0, 60, 80, Inf),
labels = c("C", "B", "A"),
right = FALSE)
[Link](marks, grade)
Dr. Sonali Mahure
breaks specifies the values to split the continuous variable on and
labels specifies the label to give to the values of the new categorical variable.
Dr. Sonali Mahure
Handling missing values,
What are Missing Values?
Missing values are values that are not known or not recorded.
In R, missing values are represented by:
NA → Not Available
NaN → Not a Number
example:
Name Age Marks
Ram 21 80
Sita NA 90
Arun 22 NA
• Here some values are missing, so they are written as NA.
• Missing values must be handled because they can affect data analysis results.
Dr. Sonali Mahure
Finding Missing Values using [Link]()
1. Using [Link]() Function for Finding Missing values:
[Link]() is a missing data detector. It scans your dataset and labels every spot as either
TRUE or FALSE based on whether the data is actually there
Returns TRUE : if the value is Missing(NA)
Returns FALSE : if the value is present
x<- c(NA, 3, 4, NA, NA, NA)
[Link](x)
Dr. Sonali Mahure
x<- c(NA, 3, 4, NA, NA, NA)
sum([Link](X))
2. Extracting values except NA or NaN values
Sometimes we want to remove missing values and keep only valid values.
x <- c(1, 2, NA, 3, NA, 4)
d <- [Link](x)
x[! d]
Dr. Sonali Mahure
Sub-setting data frames,
Sub-setting means selecting only some part of the data from a dataset. Instead of
using the entire data frame.
This can also be used to drop columns from a data frame.
Syntax: subset(df, expr)
df: Data frame used 1) Extract marks column were students marks are
expr: Condition for subset
greater than 80
Student_Name Age Marks
Complete Ram 21 80
Dataset
Example Puneeth 20 90
Arun 22 75
Ashok 19 79
Vinay 22 98
Nani 24 81
Dr. Sonali Mahure
students <- [Link](
Name=c("Ram","Puneeth","Arun","Ashok","vinay","
Nani"),
Age=c(21,20,22,19,22,24),
Marks=c(80,90,75,79,98,81)
)
print(students) Output :
result <- subset(students, Marks > 80, select =
Age)
print(result)
Dr. Sonali Mahure
Appending and merging data frames,
Appending means adding rows of one data frame to another data frame. It is also called
stacking or row binding.
To use Appending both data frames must have the same columns.
df1 <- [Link](ID = 1:3, Value = c("A", "B", "C"))
print(df1)
df2 <- [Link](ID = 4:6, Value = c("D", "E", "F"))
print(df2)
combined_df <- rbind(df1, df2)
print(combined_df)
Dr. Sonali Mahure
Drawback of rbind()
df1 <- [Link](ID=c(1,2), Name=c("Ram",“varun"))
df2 <- [Link](ID=c(3,4), Age=c(21,22))
combined_df <- rbind(df1, df2)
print(combined_df)
Output
To Overcome the drawback of rbind() we use bind_rows()
Dr. Sonali Mahure
bind_rows() (dplyr package): A more flexible alternative to rbind(), bind_rows() can
handle data frames with differing columns by filling missing columns with NA.
[Link]("dplyr") # install once
library(dplyr)
df1 <- [Link](ID=c(1,2), Name=c("Ram",“puneeth"))
df2 <- [Link](ID=c(3,4), Age=c(21,22))
bind_rows(df1, df2)
rbind() : works only when columns are same
bind_rows() : works even when columns are different
Dr. Sonali Mahure
Merging Data Frames
What is Merging?
Merging means combining two data frames using a common column.
So merging works like joining tables in a database.
df_a <- [Link](ID = c(1, 2, 3), Name = c("Alice", "Bob", "Charlie"))
df_b <- [Link](ID = c(2, 3, 4), Age = c(25, 30, 35))
merged_inner <- merge(df_a, df_b, by = "ID") # Inner join
merged_full <- merge(df_a, df_b, by = "ID", all = TRUE) # Full outer join
Dr. Sonali Mahure
Split data frames
Splitting a data frame means dividing the dataset into smaller parts.
Example:
A dataset of 10 students can be split into: , referred as all
first 5 students columns
next 5 students.
Syntax:
data-frame[start-row-num : end-row-num ,]
Dr. Sonali Mahure
students <- [Link](
Name=c("Ram","Sita","Arun","Nani","Vinay"),
Age=c(21,20,22,24,23),
Marks=c(80,90,75,88,95)
)
print(students)
part1 <- students[1:3 , ]
print(part1)
Dr. Sonali Mahure
Stack and unstack data frames
The stack() function converts data from wide format into long format. It means if data has
multiple columns, stack() will combine them into one column.
df <- [Link]( df <- [Link](
GroupA = c(10,20), GroupA = c(10,20),
GroupB = c(30,40), GroupB = c(30,40),
GroupC = c(50,60) GroupC = c(50,60))
) print(df)
long_df <- stack(df)
print(df) print(long_df)
Dr. Sonali Mahure
Unstacking Data Frames (Long to Wide Format):
The unstack() function reverses the stack() operation, converting a "long" format
data frame back into a "wide" format.
df <- [Link](
df <- [Link]( GroupA = c(10,20),
GroupA = c(10,20),
GroupB = c(30,40),
GroupB = c(30,40),
GroupC = c(50,60)) GroupC = c(50,60))
print(df)
long_df <- stack(df)
long_df <- stack(df)
print(long_df) print(long_df)
wide_df <- unstack(long_df)
print(wide_df)
Dr. Sonali Mahure
Practice Questions
1) Transform Continuous Variable → Categorical Variable
A teacher has recorded the marks of students as marks <- c(85, 72, 40, 91, 66). Write an
R program to convert these continuous marks into categories such that marks ≥ 80 are
"A", marks between 60 and 79 are "B", and marks below 60 are "C". Display the marks
and the corresponding grade.
Dr. Sonali Mahure
Practice Questions
2) Handling Missing Values using [Link]()A dataset contains the values x <- c(10, NA, 25,
NA, 40, 50) where some values are missing. Write an R program to identify the missing
values using [Link]() and extract only the values that are not missing.
Dr. Sonali Mahure
Practice Questions
3) Subsetting Data Frame
Create a data frame named students containing Name = c("Ram","Sita","Arun","Nani"),
Age = c(21,20,22,23) and Marks = c(80,90,75,85). Write an R program using the
subset() function to display only the rows where the student marks are greater than 80.
Dr. Sonali Mahure
Practice Questions
4) Appending using rbind()Create two data frames df1 and df2. Let df1 contain ID =
c(1,2) and Name = c("Ram","Sita"), and df2 contain ID = c(3,4) and Name =
c("Arun","Nani"). Write an R program to append these two data frames using rbind()
and display the combined result.
Dr. Sonali Mahure
Practice Questions
5) Appending using bind_rows() with One Different ColumnCreate two data frames
where df1 contains ID = c(1,2) and Name = c("Ram","Sita"), while df2 contains ID =
c(3,4) and Age = c(21,22). Write an R program using bind_rows() from the dplyr
package to combine these two data frames and observe how the missing values are
handled.
Dr. Sonali Mahure
Practice Questions
6) Merging Data Frames using Inner Join and Outer Join
Create two data frames where df_a contains ID = c(1,2,3) and Name =
c("Alice","Bob","Charlie"), and df_b contains ID = c(2,3,4) and Age = c(25,30,35). Write
an R program to merge these data frames using merge() to perform both an inner join
and a full outer join based on the column ID.
Dr. Sonali Mahure
Practice Questions
7) Split Data Frame
Create a data frame named students containing Name =
c("Ram","Sita","Arun","Nani","Vinay"), Age = c(21,20,22,24,23) and Marks =
c(80,90,75,88,95). Write an R program to split the data frame and display only the first
three rows using row indexing.
Dr. Sonali Mahure
Practice Questions
8) Stack Data Frame
Create a data frame with three columns GroupA = c(10,20), GroupB = c(30,40) and
GroupC = c(50,60). Write an R program to convert this wide format data into long
format using the stack() function and display the resulting data frame.
Dr. Sonali Mahure
Practice Questions
9) Unstack Data Frame
Using the data frame obtained after applying the stack() function in the previous
question, write an R program to convert the data back into the original wide format
using the unstack() function.
Dr. Sonali Mahure
Lab Progams / Hands on:
1. Write a R program to get the first 10 Fibonacci numbers.
2. Write a R program to find the maximum and the minimum value of a given vector.
3. Write a R program to get all prime numbers up to a given number
4. Write a R program to get the unique elements of a given string and unique numbers
of vector
Dr. Sonali Mahure
1. Write a R program to get the first 10 Fibonacci numbers.
n <- 10
a <- 0
b <- 1
print(a)
print(b)
for(i in 3:n)
{
c <- a + b
print(c)
a <- b
b <- c
}
Dr. Sonali Mahure
2. Write a R program to find the maximum and the minimum value of a given vector.
vec <- c(12,45,7,89,23,56)
max_val <- max(vec)
min_val <- min(vec)
print(paste("Maximum value:", max_val))
print(paste("Minimum value:", min_val))
Dr. Sonali Mahure
3. Prime Numbers
num <- 20
for(i in 2:num){
flag <- 1
for(j in 2:(i-1)){
if(i %% j == 0){
flag <- 0
break
}}
if(flag == 1)
{
print(i)
}}
Dr. Sonali Mahure