The Wayback Machine - https://web.archive.org/web/20240926185120/https://www.geeksforgeeks.org/data-analysis-using-r/
Open In App

Data analysis using R

Last Updated : 04 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Data Analysis is a subset of data analytics, it is a process where the objective has to be made clear, collect the relevant data, preprocess the data, perform analysis(understand the data, explore insights), and then visualize it. The last step visualization is important to make people understand what’s happening in the firm.

Steps involved in data analysis:

 

The process of data analysis would include all these steps for the given problem statement. Example- Analyze the products that are being rapidly sold out and details of frequent customers of a retail shop.

  • Defining the problem statement – Understand the goal, and what is needed to be done. In this case, our problem statement is – “The product is mostly sold out and list of customers who often visit the store.” 
  • Collection of data –  Not all the company’s data is necessary, understand the relevant data according to the problem. Here the required columns are product ID, customer ID, and date visited.
  • Preprocessing – Cleaning the data is mandatory to put it in a structured format before performing analysis. 
  1. Removing outliers( noisy data).
  2. Removing null or irrelevant values in the columns. (Change null values to mean value of that column.)
  3. If there is any missing data, either ignore the tuple or fill it with a mean value of the column.

Data Analysis using the Titanic dataset

You can download the titanic dataset (it contains data from real passengers of the titanic)from here. Save the dataset in the current working directory, now we will start analysis (getting to know our data).

R
titanic=read.csv("train.csv")
head(titanic)

Output:

  PassengerId Survived Pclass                                         Name    Sex
1 892 0 3 Kelly, Mr. James male
2 893 1 3 Wilkes, Mrs. James (Ellen Needs) female
3 894 0 2 Myles, Mr. Thomas Francis male
4 895 0 3 Wirz, Mr. Albert male
5 896 1 3 Hirvonen, Mrs. Alexander (Helga E Lindqvist) female
6 897 0 3 Svensson, Mr. Johan Cervin male
Age SibSp Parch Ticket Fare Cabin Embarked
1 34.5 0 0 330911 7.8292 Q
2 47.0 1 0 363272 7.0000 S
3 62.0 0 0 240276 9.6875 Q
4 27.0 0 0 315154 8.6625 S
5 22.0 1 1 3101298 12.2875 S
6 14.0 0 0 7538 9.2250 S

Our dataset contains all the columns like name, age, gender of the passenger and class they have traveled in, whether they have survived or not, etc. To understand the class(data type) of each column sapply() method can be used.

R
sapply(train, class)

Output:

PassengerId    Survived      Pclass        Name         Sex         Age 
"integer" "integer" "integer" "character" "character" "numeric"
SibSp Parch Ticket Fare Cabin Embarked
"integer" "integer" "character" "numeric" "character" "character"

We can categorize the value “survived” into “dead” to 0 and “alive” to 1 using factor() function.

R
train$Survived=as.factor(train$Survived)
train$Sex=as.factor(train$Sex)
sapply(train, class)

Output:

PassengerId    Survived      Pclass        Name         Sex         Age 
"integer" "factor" "integer" "character" "factor" "numeric"
SibSp Parch Ticket Fare Cabin Embarked
"integer" "integer" "character" "numeric" "character" "character"

We analyze data using a summary of all the columns, their values, and data types. summary() can be used for this purpose.

R
summary(train)

Output:

  PassengerId     Survived     Pclass          Name               Sex     
Min. : 892.0 0:266 Min. :1.000 Length:418 female:152
1st Qu.: 996.2 1:152 1st Qu.:1.000 Class :character male :266
Median :1100.5 Median :3.000 Mode :character
Mean :1100.5 Mean :2.266
3rd Qu.:1204.8 3rd Qu.:3.000
Max. :1309.0 Max. :3.000

Age SibSp Parch Ticket
Min. : 0.17 Min. :0.0000 Min. :0.0000 Length:418
1st Qu.:21.00 1st Qu.:0.0000 1st Qu.:0.0000 Class :character
Median :27.00 Median :0.0000 Median :0.0000 Mode :character
Mean :30.27 Mean :0.4474 Mean :0.3923
3rd Qu.:39.00 3rd Qu.:1.0000 3rd Qu.:0.0000
Max. :76.00 Max. :8.0000 Max. :9.0000
NA's :86
Fare Cabin Embarked
Min. : 0.000 Length:418 Length:418
1st Qu.: 7.896 Class :character Class :character
Median : 14.454 Mode :character Mode :character
Mean : 35.627
3rd Qu.: 31.500
Max. :512.329
NA's :1

From the above summary we can extract below observations:

  • Total passengers:  891
  • The number of total people who survived:  342
  • Number of total people dead:  549
  • Number of males in the titanic:  577
  • Number of females in the titanic:  314
  • Maximum age among all people in titanic:  80
  • Median age:  28

Preprocessing of the data is important before analysis, so null values have to be checked and removed.

R
sum(is.na(train))

Output:

177
R
dropnull_train=train[rowSums(is.na(train))<=0,]
  • dropnull_train contains only 631 rows because (total rows in dataset (808) – null value rows (177) = remaining rows (631) )
  • Now we will divide survived and dead people into a separate list from 631 rows.
R
survivedlist=dropnull_train[dropnull_train$Survived == 1,]
notsurvivedlist=dropnull_train[dropnull_train$Survived == 0,]

Now we can visualize the number of males and females dead and survived using bar plots, histograms, and piecharts.

R
mytable <- table(titanic$Survived)
lbls <- paste(names(mytable), "\n", mytable, sep="")
pie(mytable,
    labels = lbls,
    main="Pie Chart of Survived column data\n (with sample sizes)") 

Output:

 

From the above pie chart, we can certainly say that there is a data imbalance in the target/Survived column.

R
hist(survivedlist$Age,
     xlab="gender",
     ylab="frequency")

Output:

 

Now let’s draw a bar plot to visualize the number of males and females who were there on the titanic ship.

R
barplot(table(notsurvivedlist$Sex),
        xlab="gender",
        ylab="frequency")

Output:

 

From the barplot above we can analyze that there are nearly 350 males, and 50 females those are not survived in titanic.

R
temp<-density(table(titanic$Fare))
plot(temp, type="n",
     main="Fare charged from Passengers")
polygon(temp, col="lightgray",
        border="gray")

Output:

 

Here we can observe that there are some passengers who are charged extremely high. So, these values can affect our analysis as they are outliers. Let’s confirm their presence using a boxplot.

R
boxplot(titanic$Fare,
        main="Fare charged from passengers")

Output:

Certainly, there are some extreme outliers present in this dataset.


Performing Clustering

  • Import required R libraries for data manipulation, clustering, and visualization.
  • Read the Titanic dataset from the specified file path.
  • Keep only the relevant columns for analysis.
  • Transform categorical variables into numeric format using factor() function.
  • Impute missing values for Age with the mean value and ensure there are no remaining missing values. Remove any rows with remaining missing values if necessary.
  • Scale the data to ensure that all features contribute equally to clustering.
  • Verify that the standardized data does not contain NaN or Inf values, which could affect clustering.
  • Use the Elbow Method to find the optimal number of clusters; if this method fails, manually try different values.
  • Run the K-means algorithm with the chosen number of clusters (e.g., k = 3) and a set seed for reproducibility.
  • Ensure that the K-means clustering results have been successfully created.
  • Append the cluster assignments to the original dataset for further analysis.
  • Create a cluster plot to visualize the results of the K-means clustering.
R
# Load necessary libraries
library(tidyverse)
library(cluster)
library(factoextra)

# Load the dataset
titanic_data <- read.csv("C:/Users/Tonmoy/Downloads/titanic.csv")

# Data preprocessing
# Remove unnecessary columns
titanic_data <- titanic_data %>%
  select(PassengerId, Survived, Pclass, Sex, Age, SibSp, Parch, Fare)

# Convert categorical variables to numeric
titanic_data$Sex <- as.numeric(factor(titanic_data$Sex))

# Handle missing values
# Impute missing values for Age
titanic_data$Age[is.na(titanic_data$Age)] <- mean(titanic_data$Age, na.rm = TRUE)

# Ensure there are no remaining missing values
missing_values <- sum(is.na(titanic_data))
print(paste("Remaining missing values after imputation:", missing_values))

# If missing values still exist, handle them (e.g., impute with mean or remove rows/columns)
if (missing_values > 0) {
  # Remove rows with remaining missing values (if any)
  titanic_data <- na.omit(titanic_data)
}

# Standardize the data
titanic_scaled <- scale(titanic_data)

# Check for NaNs or Infs in the scaled data
if (any(is.nan(titanic_scaled)) || any(is.infinite(titanic_scaled))) {
  stop("Scaled data contains NaN or Inf values")
}

# Double-check the data for any anomalies
print(summary(titanic_scaled))

# Determine the optimal number of clusters
# If Elbow method still fails, manually try different k values
fviz_nbclust(titanic_scaled, kmeans, method = "wss") + labs(subtitle = "Elbow Method")

# Perform K-means clustering with the optimal number of clusters (e.g., k = 3)
set.seed(123)
kmeans_result <- kmeans(titanic_scaled, centers = 3, nstart = 25)

# Check if kmeans_result was created successfully
if (!exists("kmeans_result")) {
  stop("K-means clustering failed to create kmeans_result")
}

# Add cluster assignments to the original dataset
titanic_data$Cluster <- kmeans_result$cluster

# Visualize the clustering
fviz_cluster(kmeans_result, data = titanic_scaled, geom = "point", stand = FALSE)

Output:

Screenshot-2024-07-21-202033

Visualize the cluster


Predictive Model

  • Load a collection of R packages for data manipulation and visualization. It includes dplyr and ggplot2, among others.
  • The caret package for training and evaluating machine learning models. It provides functions for data splitting (createDataPartition), model training (train), and performance evaluation (confusionMatrix).
  • Loads the dataset from a specified file path into a data frame.
  • Chooses relevant columns from the dataset to use for modeling. Here, it selects columns related to survival status and passenger features.
  • Converts the Sex variable into a factor, which is then converted to numeric values. This is necessary because logistic regression models require numerical input.
  • Computes the mean age (excluding missing values) to impute the missing values in the Age column.
  • Counts remaining missing values.
  • Removes rows with any remaining missing values.
  • Converts the Survived variable to a factor. This is essential for classification tasks in logistic regression.
  • Ensures reproducibility of the data split.
  • Creates an 80-20 split of the data into training and testing sets.
  • Trains a logistic regression model (method = “glm”) with a binomial family for binary classification.
  • Generates predictions on the test set using the trained model.
  • Ensures that the factor levels of titanic_test$Survived match those of predictions.
  • Computes and prints the confusion matrix to evaluate model performance.
R
# Load necessary libraries
library(tidyverse)
library(caret)  # For createDataPartition, train, and confusionMatrix

# Load the dataset
titanic_data <- read.csv("C:/Users/Tonmoy/Downloads/titanic.csv")

# Data preprocessing
titanic_data <- titanic_data %>%
  select(Survived, Pclass, Sex, Age, SibSp, Parch, Fare)

# Convert categorical variables to numeric
titanic_data$Sex <- as.numeric(factor(titanic_data$Sex))

# Handle missing values by imputing with mean for Age
titanic_data$Age[is.na(titanic_data$Age)] <- mean(titanic_data$Age, na.rm = TRUE)

# Check for remaining missing values
missing_values <- sum(is.na(titanic_data))
print(paste("Remaining missing values after imputation:", missing_values))

# Remove rows with remaining missing values (if any)
if (missing_values > 0) {
  titanic_data <- na.omit(titanic_data)
}

# Convert Survived to factor for classification
titanic_data$Survived <- as.factor(titanic_data$Survived)

# Split the data into training and testing sets
set.seed(123)
trainIndex <- createDataPartition(titanic_data$Survived, p = .8, list = FALSE)
titanic_train <- titanic_data[trainIndex, ]
titanic_test  <- titanic_data[-trainIndex, ]

# Train a logistic regression model
model <- train(Survived ~ ., data = titanic_train, method = "glm", family = binomial)


# Make predictions on the test set
predictions <- predict(model, titanic_test)

# Ensure both factors have the same levels
levels(titanic_test$Survived) <- levels(predictions)

# Evaluate the model
conf_matrix <- confusionMatrix(predictions, titanic_test$Survived)
print(conf_matrix)

Output:

Confusion Matrix and Statistics

Reference
Prediction 0 1
0 53 0
1 0 30

Accuracy : 1
95% CI : (0.9565, 1)
No Information Rate : 0.6386
P-Value [Acc > NIR] : < 2.2e-16

Kappa : 1

Mcnemar's Test P-Value : NA

Sensitivity : 1.0000
Specificity : 1.0000
Pos Pred Value : 1.0000
Neg Pred Value : 1.0000
Prevalence : 0.6386
Detection Rate : 0.6386
Detection Prevalence : 0.6386
Balanced Accuracy : 1.0000

'Positive' Class : 0

Explanation of the output –

  • Accuracy: 100% – The model predicts all test cases correctly.
  • Sensitivity: 100% – The model identifies all positive cases correctly.
  • Specificity: 100% – The model identifies all negative cases correctly.
  • Kappa: 1 – A measure of agreement between the predicted and observed classifications.
  • The code trains a logistic regression model to predict survival based on various features of the Titanic dataset.
  • The model shows perfect accuracy, but this might be due to issues in the data or its split. Further validation is recommended.





Previous Article
Next Article

Similar Reads

Factor Analysis | Data Analysis
Factor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean in Factor Analysis?How to do Factor Analysis (Facto
13 min read
Data Analysis through Ethnographic Content Analysis
Ethnographic Content Analysis (ECA) is a qualitative research method that combines the systematic approach of content analysis with the depth and contextual richness of ethnography. This hybrid methodology is particularly useful for exploring complex social phenomena, uncovering patterns, and understanding cultural contexts. In this article, we wil
8 min read
Difference Between Factor Analysis and Principal Component Analysis
Factor Analysis (FA) and Principal Component Analysis (PCA) are two pivotal techniques used for data reduction and structure detection. Despite their similarities, they serve distinct purposes and operate under different assumptions. This article explores the key differences between FA and PCA. Understanding Principal Component Analysis (PCA)Princi
4 min read
Stock Data Analysis and Data Visualization with Quantmod in R
Analysis of historical stock price and volume data is done in order to obtain knowledge, make wise decisions, and create trading or investment strategies. The following elements are frequently included in the examination of stock data in the R Programming Language. Historical Price Data: Historical price data contains information about a stock's op
8 min read
Difference Between Data Analysis and Data Interpretation
Data analysis and Data Interpretation come pretty close; the only difference is in their roles in the data-driven process. In the process, it is all about the systematic inspection, cleaning, transformation, and modelling of the data to discover useful information, patterns, or trends—it mainly dissects raw data into smaller parts to make sense of
6 min read
Covid-19 Data Analysis Using Tableau
Tableau is a software used for data visualization and analysis. it's a tool that can make data-analysis easier. Visualizations can be in the form of worksheets or dashboard. Here are some simple steps in creating worksheets and dashboard using covid-19 dataset in Tableau tool. Data link: https://data.world/covid-19-data-resource-hub/covid-19-case-c
4 min read
Olympics Data Analysis Using Python
In this article, we are going to see the Olympics analysis using Python. The modern Olympic Games or Olympics are leading international sports events featuring summer and winter sports competitions in which thousands of athletes from around the world participate in a variety of competitions. The Olympic Games are considered the world's foremost spo
4 min read
YouTube Data Scraping, Preprocessing and Analysis using Python
YouTube is one of the oldest and most popular video distribution platforms in the world. We can't even imagine the video content available here. It has billion of users and viewers, which keeps on increasing every passing minute. Since its origins, YouTube and its content have transformed very much. Now we have SHORTS, likes, and many more features
5 min read
Quick Guide to Exploratory Data Analysis Using Jupyter Notebook
Before we pass our data into the machine learning model, data is pre-processed so that it is compatible to pass inside the model. To pre-process this data, some operations are performed on the data which is collectively called Exploratory Data Analysis(EDA). In this article, we'll be looking at how to perform Exploratory data analysis using jupyter
13 min read
Medical Analysis Using Python: Revolutionizing Healthcare with Data Science
In recent years, the intersection of healthcare and technology has given rise to groundbreaking advancements in medical analysis. Imagine a doctor faced with lots of patient information and records, searching for clues to diagnose complex disease? Analysing this data is like putting together a medical puzzle, and it's important for doctors to see t
9 min read
Finance Tracker Dashboard in Data Analysis Using R
Managing personal finances is essential for maintaining financial health and achieving financial goals. Building a personal finance tracker dashboard in R can provide valuable insights into income, expenses, savings, and investment performance. In this article, we'll outline the steps to create a simple yet effective personal finance tracker dashbo
6 min read
Data Analysis Using Monte Carlo Simulation
Monte Carlo Simulation is a powerful statistical technique used to understand the impact of risk and uncertainty in prediction and modeling problems. Named after the Monte Carlo Casino in Monaco, this method relies on repeated random sampling to obtain numerical results. It is widely used in fields such as finance, engineering, supply chain managem
6 min read
IPL 2023 Data Analysis using Pandas AI
We are already familiar with performing data analysis using Pandas, in this article, we will see how we can leverage the power of PandasAI to perform analysis on IPL 2023 Auction dataset. We have already covered the Introduction to PandasAI. You can check out our blog post here. Data Analysis using Pandas AIStep 1: Install pandasai and openai libra
6 min read
Uber Rides Data Analysis using Python
In this article, we will use Python and its different libraries to analyze the Uber Rides Data. Importing LibrariesThe analysis will be done using the following libraries :  Pandas:  This library helps to load the data frame in a 2D array format and has multiple functions to perform analysis tasks in one go.Numpy: Numpy arrays are very fast and can
5 min read
Multidimensional data analysis in Python
Multi-dimensional data analysis is an informative analysis of data which takes many relationships into account. Let's shed light on some basic techniques used for analysing multidimensional/multivariate data using open source libraries written in Python. Find the link for data used for illustration from here.Following code is used to read 2D tabula
5 min read
Machine Learning and Analysis of Site Position Data
The content has been removed as per the author's request.
1 min read
Data Preprocessing, Analysis, and Visualization for building a Machine learning model
In this article, we are going to see the concept of Data Preprocessing, Analysis, and Visualization for building a Machine learning model. Business owners and organizations use Machine Learning models to predict their Business growth. But before applying machine learning models, the dataset needs to be preprocessed. So, let's import the data and st
5 min read
What is Univariate, Bivariate & Multivariate Analysis in Data Visualisation?
Data Visualisation is a graphical representation of information and data. By using different visual elements such as charts, graphs, and maps data visualization tools provide us with an accessible way to find and understand hidden trends and patterns in data. In this article, we are going to see about the univariate, Bivariate & Multivariate An
3 min read
SQL vs R - Which to use for Data Analysis?
Data Analysis, as the name suggests, means the evaluation or examination of the data, in Layman’s terms. The answer to the question as to why Data Analysis is important lies in the fact that deriving insights from the data and understanding them are extremely crucial for organizations and businesses across the globe for profits. Data Analysis essen
5 min read
Graphical Data Analysis in R
Graphical Data Analysis (GDA) is a powerful tool that helps us to visualize and explore complex data sets. R is a popular programming language for GDA as it has a wide range of built-in functions for producing high-quality visualizations. In this article, we will explore some of the most commonly used GDA techniques in the R Programming Language. F
7 min read
SweetViz | Automated Exploratory Data Analysis (EDA)
SweetViz is an open-source Python library, this is used for automated exploratory data analysis (EDA), it helps data analysts/scientists quickly generate beautiful & highly detailed visualizations. The output, we get is a fully self-contained HTML application. The system built reports around quickly visualizing the target values & comparing
4 min read
Geospatial Data Analysis with R
Geospatial data analysis involves working with data that has a geographic or spatial component. It allows us to analyze and visualize data in the context of its location on the Earth's surface. R Programming Language is a popular open-source programming language, that offers a wide range of packages and tools for geospatial data analysis. fundament
5 min read
Data analysis and Visualization with Python
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. In this article, I have used Pandas to analyze data on Country Data.csv file from UN public Data Sets of a popular 'statweb.stanford.ed
4 min read
What is Data Munging in Analysis?
Data is the lifeblood of the digital age, but raw data in its natural state is often messy, inconsistent, and laden with defects. Before analysis can commence, rigorous data munging is required to transform the raw material of data into a strategic asset that fuels impactful insights. In this article, we'll delve into the process of transformation
11 min read
How Much ML is Needed for Data Analysis?
Data analysis has become a critical component of decision-making across industries. With the exponential growth of data, businesses are increasingly looking for valuable insights to stay competitive. Here's where machine learning comes in. Machine learning provides advanced analytical capabilities to uncover patterns, make predictions, and optimize
12 min read
Top Common Data Analysis Challenges Facing Businesses
Data analysis is the act of converting raw data into relevant insights that can help organizations make better decisions and improve performance. Business intelligence may get a competitive advantage in the market, find new possibilities, and enhance its operations with the use of data analysis. As companies strive to harness the power of data to g
15 min read
Univariate, Bivariate and Multivariate data and its analysis
In this article,we will be discussing univariate, bivariate, and multivariate data and their analysis. Univariate data: Univariate data refers to a type of data in which each observation or data point corresponds to a single variable. In other words, it involves the measurement or observation of a single characteristic or attribute for each individ
5 min read
What is Geospatial Data Analysis?
Have you ever used a ride-sharing app to find the nearest drivers, pinpointed a meeting location on a map, or checked a weather forecast showing precipitation patterns? If so, you have already interacted with geospatial analysis! This widespread, versatile field integrates geography, statistics, and data science to extract powerful insights from lo
11 min read
Violin Plot for Data Analysis
Data visualization is instrumental in understanding and interpreting data trends. Various visualization charts aid in comprehending data, with the violin plot standing out as a powerful tool for visualizing data distribution. This article aims to explore the fundamentals, implementation, and interpretation of violin plots. Before applying any trans
8 min read
What is Quantitative Data Analysis?
Quantitative data analysis is like using a magnifying glass to understand numbers better. Quantitative data analysis helps look closely at these numbers to see if there are any interesting patterns or trends hiding in them. In this article, let's discuss Quantitative Data Analysis in depth. What is Quantitative Data Analysis?Quantitative data analy
7 min read