Experiments
Experiments
EXPERIMENT NO: 01
Theory:
Data:
The quantities, characters, or symbols on which operations are performed by a computer, which
may be stored and transmitted in the form of electrical signals and recorded on magnetic, optical,
or mechanical recording media.
Big Data:
Big Data is a collection of data that is huge in volume, yet growing exponentially with time. It is
a data with so large size and complexity that none of traditional data management tools can store
it or process it efficiently. Big data is also a data but with huge size.
The New York Stock Exchange generates about one terabyte of new trade data per day.
Social Media:
The statistic shows that 500+terabytes of new data get ingested into the databases of
social media site Facebook, every day. This data is mainly generated in terms of photo
and video uploads, message exchanges, putting comments etc.
Jet engine
A single Jet engine can generate 10+terabytes of data in 30 minutes of flight time. With
many thousand flights per day, generation of data reaches up to many Petabytes.
1. Structured
2. Unstructured
3. Semi-structured
Structured:
Any data that can be stored, accessed and processed in the form of fixed format is termed
as a 'structured' data. Over the period of time, talent in computer science has achieved
greater success in developing techniques for working with such kind of data (where the
format is well known in advance) and also deriving value out of it. However, nowadays,
we are foreseeing issues when a size of such data grows to a huge extent, typical sizes are
being in the rage of multiple zettabytes.
Unstructured:
Any data with unknown form or the structure is classified as unstructured data. In
addition to the size being huge, un-structured data poses multiple challenges in terms of
its processing for deriving value out of it. A typical example of unstructured data is a
heterogeneous data source containing a combination of simple text files, images, videos
etc. Now day organizations have wealth of data available with them but unfortunately,
they don't know how to derive value out of it since this data is in its raw form or
unstructured format.
Semi-structured:
Semi-structured data can contain both the forms of data. We can see semi-structured data
as a structured in form but it is actually not defined with e.g. a table definition in
relational DBMS. Example of semi-structured data is a data represented in an XML file.
<rec><name>Prashant Rao</name><sex>Male</sex><age>35</age></rec>
<rec><name>Seema R.</name><sex>Female</sex><age>41</age></rec>
<rec><name>Satish Mane</name><sex>Male</sex><age>29</age></rec>
<rec><name>Subrato Roy</name><sex>Male</sex><age>26</age></rec>
<rec><name>Jeremiah J.</name><sex>Male</sex><age>35</age></rec>
Volume
Variety
Velocity
Variability
(i) Volume – The name Big Data itself is related to a size which is enormous. Size of data
plays a very crucial role in determining value out of data. Also, whether a particular data can
actually be considered as a Big Data or not, is dependent upon the volume of data.
Hence, 'Volume' is one characteristic which needs to be considered while dealing with Big
Data.
(ii) Variety – Variety refers to heterogeneous sources and the nature of data, both structured
and unstructured. During earlier days, spreadsheets and databases were the only sources of
data considered by most of the applications. Nowadays, data in the form of emails, photos,
videos, monitoring devices, PDFs, audio, etc. are also being considered in the analysis
applications. This variety of unstructured data poses certain issues for storage, mining and
analyzing data.
(iii) Velocity – The term 'velocity' refers to the speed of generation of data. How fast the data
is generated and processed to meet the demands, determines real potential in the data. Big
Data Velocity deals with the speed at which data flows in from sources like business
processes, application logs, networks, and social media sites, sensors, Mobile devices, etc.
The flow of data is massive and continuous.
(iv) Variability – This refers to the inconsistency which can be shown by the data at times,
thus hampering the process of being able to handle and manage the data effectively.
Apache Hadoop:
Apache Hadoop is an open source software framework used to develop data processing
applications which are executed in a distributed computing environment.
Applications built using HADOOP are run on large data sets distributed across clusters of
commodity computers. Commodity computers are cheap and widely available. These are mainly
useful for achieving greater computational power at low cost.
Similar to data residing in a local file system of a personal computer system, in Hadoop, data
resides in a distributed file system which is called as a Hadoop Distributed File system. The
processing model is based on 'Data Locality' concept wherein computational logic is sent to
cluster nodes(server) containing data. This computational logic is nothing, but a compiled
version of a program written in a high-level language such as Java. Such a program, processes
data stored in Hadoop HDFS.
Hadoop Architecture:
Hadoop has a Master-Slave Architecture for data storage and distributed data processing
using MapReduce and HDFS methods.
NameNode:
NameNode represented every files and directory which is used in the namespace
DataNode:
DataNode helps you to manage the state of an HDFS node and allows you to interacts
with the blocks
MasterNode:
The master node allows you to conduct parallel processing of data using Hadoop
MapReduce.
Slave node:
The slave nodes are the additional machines in the Hadoop cluster which allows you to
store data to conduct complex calculations. Moreover, all the slave node comes with Task
Tracker and a DataNode. This allows you to synchronize the processes with the
NameNode and Job Tracker respectively.
Features Of Hadoop:
As Big Data tends to be distributed and unstructured in nature, HADOOP clusters are
best suited for analysis of Big Data. Since it is processing logic (not the actual data) that
flows to the computing nodes, less network bandwidth is consumed. This concept is
called as data locality concept which helps increase the efficiency of Hadoop based
applications.
• Scalability
HADOOP clusters can easily be scaled to any extent by adding additional cluster nodes
and thus allows for the growth of Big Data. Also, scaling does not require modifications
to application logic.
• Fault Tolerance
HADOOP ecosystem has a provision to replicate the input data on to other cluster nodes.
That way, in the event of a cluster node failure, data processing can still proceed by using
data stored on another cluster node.
Conclusion:
Sample Questions:
1) What is Hadoop.
EXPERIMENT NO: 02
Theory:
Re-login as hduser_
su - hduser_
ssh localhost
Note: Please note, if you see below error in response to 'ssh localhost', then there is a
possibility that SSH is not available on this system-
To resolve this -
Select Stable
Once a download is complete, navigate to the directory containing the tar file
Enter,
#Set HADOOP_HOME
export HADOOP_HOME=<Installation Directory of Hadoop>
#Set JAVA_HOME
export JAVA_HOME=<Installation Directory of Java>
# Add bin/ directory of Hadoop to PATH
export PATH=$PATH:$HADOOP_HOME/bin
. ~/.bashrc
With
<property>
<name>[Link]</name>
<value>/app/hadoop/tmp</value>
<description>Parent directory for other temporary directories.</description>
</property>
<property>
<name>[Link] </name>
<value>hdfs://localhost:54310</value>
<description>The name of the default file system. </description>
</property>
Before you begin with these configurations, lets set HADOOP_HOME path
And Enter
export HADOOP_HOME=/home/guru99/Downloads/Hadoop
Next enter
sudo cp $HADOOP_HOME/etc/hadoop/[Link]
$HADOOP_HOME/etc/hadoop/[Link]
<property>
<name>[Link]</name>
<value>localhost:54311</value>
<description>MapReduce job tracker runs at this host and port.
</description>
</property>
<property>
<name>[Link]</name>
<value>1</value>
<description>Default block replication.</description>
</property>
<property>
<name>[Link]</name>
<value>/home/hduser_/hdfs</value>
</property>
Step 4) Before we start Hadoop for the first time, format HDFS using below command
$HADOOP_HOME/sbin/[Link]
$HADOOP_HOME/sbin/[Link]
Using 'jps' tool/command, verify whether all the Hadoop related processes are running or
not.
If Hadoop has started successfully then an output of jps should show NameNode,
NodeManager, ResourceManager, SecondaryNameNode, DataNode.
$HADOOP_HOME/sbin/[Link]
$HADOOP_HOME/sbin/[Link]
Conclusion:
Sample Questions:
1) Explain Hadoop distributed file system.
EXPERIMENT NO: 03
Theory:
MapReduce is a software framework and programming model used for processing huge
amounts of data. MapReduce program work in two phases, namely, Map and Reduce. Map tasks
deal with splitting and mapping of data while Reduce tasks shuffle and reduce the data.
Hadoop is capable of running MapReduce programs written in various languages: Java, Ruby,
Python, and C++. The programs of Map Reduce in cloud computing are parallel in nature, thus
are very useful for performing large-scale data analysis using multiple machines in the cluster.
The input to each phase is key-value pairs. In addition, every programmer needs to specify two
functions: map function and reduce function.
The whole process goes through four phases of execution namely, splitting, mapping, shuffling,
and reducing.
Consider you have following input data for your MapReduce in Big data Program
MapReduce Architecture
The final output of the MapReduce task is
bad 1
Class 1
good 1
Hadoop 3
is 2
to 1
Welcome 1
The data goes through the following phases of MapReduce in Big Data
Computer Science & Engineering Page 26
DYPTC,Talsande.
Input Splits:
An input to a MapReduce in Big Data job is divided into fixed-size pieces called input
splits Input split is a chunk of the input that is consumed by a single map
Mapping
This is the very first phase in the execution of map-reduce program. In this phase data in each
split is passed to a mapping function to produce output values. In our example, a job of mapping
phase is to count a number of occurrences of each word from input splits (more details about
input-split is given below) and prepare a list in the form of <word, frequency>
Shuffling
This phase consumes the output of Mapping phase. Its task is to consolidate the relevant records
from Mapping phase output. In our example, the same words are clubed together along with their
respective frequency.
Reducing
In this phase, output values from the Shuffling phase are aggregated. This phase combines values
from Shuffling phase and returns a single output value. In short, this phase summarizes the
complete dataset.
In our example, this phase aggregates the values from Shuffling phase i.e., calculates total
occurrences of each word.
MapReduce Architecture :
One map task is created for each split which then executes map function for each record
in the split.
It is always beneficial to have multiple splits because the time taken to process a split is
small as compared to the time taken for processing of the whole input. When the splits
are smaller, the processing is better to load balanced since we are processing the splits in
parallel.
However, it is also not desirable to have splits too small in size. When splits are too
small, the overload of managing the splits and map task creation begins to dominate the
total job execution time.
For most jobs, it is better to make a split size equal to the size of an HDFS block (which
is 64 MB, by default).
Execution of map tasks results into writing output to a local disk on the respective node
and not to HDFS.
Reason for choosing local disk over HDFS is, to avoid replication which takes place in
case of HDFS store operation.
Map output is intermediate output which is processed by reduce tasks to produce the final
output.
Once the job is complete, the map output can be thrown away. So, storing it in HDFS
with replication becomes overkill.
In the event of node failure, before the map output is consumed by the reduce task,
Hadoop reruns the map task on another node and re-creates the map output.
Reduce task doesn't work on the concept of data locality. An output of every map task is
fed to the reduce task. Map output is transferred to the machine where reduce task is
running.
On this machine, the output is merged and then passed to the user-defined reduce
function.
Unlike the map output, reduce output is stored in HDFS (the first replica is stored on the
local node and other replicas are stored on off-rack nodes). So, writing the reduce output
Hadoop divides the job into tasks. There are two types of tasks:
as mentioned above.
The complete execution process (execution of Map and Reduce tasks, both) is controlled by two
types of entities called a
1. Jobtracker: Acts like a master (responsible for complete execution of submitted job)
2. Multiple Task Trackers: Acts like slaves, each of them performing the job
For every job submitted for execution in the system, there is one Jobtracker that resides
on Namenode and there are multiple tasktrackers which reside on Datanode.
A job is divided into multiple tasks which are then run onto multiple data nodes in a
cluster.
It is the responsibility of job tracker to coordinate the activity by scheduling tasks to run
on different data nodes.
Execution of individual task is then to look after by task tracker, which resides on every
data node executing part of the job.
Task tracker's responsibility is to send the progress report to the job tracker.
In addition, task tracker periodically sends 'heartbeat' signal to the Jobtracker so as to
notify him of the current state of the system.
Thus job tracker keeps track of the overall progress of each job. In the event of task
failure, the job tracker can reschedule it on a different task tracker.
Conclusion:
Sample Questions:
1) What is MapReduce.
2) Explain Terminology of MapReduce.
EXPERIMENT NO: 04
Theory:
HDFS:
HDFS is a distributed file system for storing very large data files, running on clusters of
commodity hardware. It is fault tolerant, scalable, and extremely simple to expand. Hadoop
comes bundled with HDFS (Hadoop Distributed File Systems).
When data exceeds the capacity of storage on a single physical machine, it becomes essential to
divide it across a number of separate machines. A file system that manages storage specific
operations across a network of machines is called a distributed file system. HDFS is one such
software.
HDFS Architecture:
HDFS cluster primarily consists of a NameNode that manages the file system Metadata and
a DataNodes that stores the actual data.
NameNode: NameNode can be considered as a master of the system. It maintains the file
system tree and the metadata for all the files and directories present in the system. Two
files 'Namespace image' and the 'edit log' are used to store metadata information.
Namenode has knowledge of all the datanodes containing data blocks for a given file,
however, it does not store block locations persistently. This information is reconstructed
every time from datanodes when the system starts.
DataNode: DataNodes are slaves which reside on each machine in a cluster and provide
the actual storage. It is responsible for serving, read and write requests for the clients.
Read/write operations in HDFS operate at a block level. Data files in HDFS are broken into
block-sized chunks, which are stored as independent units. Default block-size is 64 MB.
HDFS operates on a concept of data replication wherein multiple replicas of data blocks are
created and are distributed on nodes throughout a cluster to enable high availability of data in the
event of node failure.
Data read request is served by HDFS, NameNode, and DataNode. Let's call the reader as a
'client'. Below diagram depicts file read operation in Hadoop.
In this section, we will understand how data is written into HDFS through files.
data, DFSOutputStream continues creating packets with this data. These packets are
enqueued into a queue which is called as DataQueue.
5. There is one more component called DataStreamer which consumes this DataQueue.
DataStreamer also asks NameNode for allocation of new blocks thereby picking desirable
DataNodes to be used for replication.
6. Now, the process of replication starts by creating a pipeline using DataNodes. In our
case, we have chosen a replication level of 3 and hence there are 3 DataNodes in the
pipeline.
7. The DataStreamer pours packets into the first DataNode in the pipeline.
8. Every DataNode in a pipeline stores packet received by it and forwards the same to the
second DataNode in a pipeline.
9. Another queue, 'Ack Queue' is maintained by DFSOutputStream to store packets which
are waiting for acknowledgment from DataNodes.
10. Once acknowledgment for a packet in the queue is received from all DataNodes in the
pipeline, it is removed from the 'Ack Queue'. In the event of any DataNode failure,
packets from this queue are used to reinitiate the operation.
11. After a client is done with the writing data, it calls a close() method (Step 9 in the
diagram) Call to close(), results into flushing remaining data packets to the pipeline
followed by waiting for acknowledgment.
12. Once a final acknowledgment is received, NameNode is contacted to tell it that the file
write operation is complete.
Conclusion:
Sample Questions:
1) Explain HDFS.
2) Describe read operation of HDFS.
3) Explain write operation of HDFS.
EXPERIMENT NO: 05
Title: Installation R-Programming environment.
Aim: Study of R- Programming Languages.
R programming is a very popular language and to work on that we have to install RGui.
Installing R to the local computer is very easy. First, we must know which operating system we
are using so that we can download it accordingly. The official site [Link]
[Link] provides installer files for major operating systems including Windows, Linux, and
Mac OS.
Install R in Windows:
Go to the official R Project website ([Link] and download the latest version
of R for Windows.
To proceed, please click the link labelled "install R for the first time."
Open your downloads folder and double-click on the R installer file that you just downloaded.
You may be required to grant access based on your security configurations. Please permit it and
continue.
Step 3: Install R
You will be prompted to specify the installation directory. The default location is C:\Program
Files\R\.
You may retain this setting and continue with the installation by clicking on Next button.
The installer will then prompt you to choose components and where to place shortcuts.
Click Next button to continue installation.
Setup has finished installing R for Windows 4.4.2. Click Finish to exit the installer.
It is essential to manually set that the PATH environment variable of your system is configured
properly.
To add the PATH environment variable, please follow these steps.
After the installation is finished, you can confirm that R has been installed correctly by opening a
command prompt (cmd) and entering the following command:
R --version
EXPERIMENT NO: 06
Title: Introduction of R Language and Study of datatypes, variables & logical operator in R
Aim: Study of fundamentals of R Language.
Theory:
R Software:
R is a programming language and free software developed by Ross Ihaka and Robert Gentleman
in 1993. R possesses an extensive catalog of statistical and graphical methods. It includes
machine learning algorithms, linear regression, time series, statistical inference to name a few.
Most of the R libraries are written in R, but for heavy computational tasks, C, C++ and Fortran
codes are preferred.
R is not only entrusted by academic, but many large companies also use R programming
language, including Uber, Google, Airbnb, Facebook and so on.
R used for:
Statistical inference
Data analysis
Machine learning algorithm
Years ago, R was a difficult language to master. The language was confusing and not as
structured as the other programming tools. To overcome this major issue, Hadley Wickham
developed a collection of packages called tidyverse. The rule of the game changed for the best.
Data manipulation become trivial and intuitive. Creating a graph was not so difficult anymore.
The best algorithms for machine learning can be implemented with R. Packages like Keras and
TensorFlow allow to create high-end machine learning technique. R also has a package to
perform Xgboost, one the best algorithm for Kaggle competition.
R can communicate with the other language. It is possible to call Python, Java, C++ in R. The
world of big data is also accessible to R. You can connect R with different databases like Spark
or Hadoop.
Finally, R has evolved and allowed parallelizing operation to speed up the computation. In fact,
R was criticized for using only one CPU at a time. The parallel package lets you to perform tasks
in different cores of the machine.
Data Types in R:
Scalars
Vectors (numerical, character, logical)
Matrices
Data frames
Lists
Basics types:
Example 1:
# Numeric
x <- 28
class(x)
Output:
## [1] "numeric"
Example 2:
# String
class(y)
Output:
## [1] "character"
Example 3:
# Boolean
z <- TRUE
class(z)
Output:
## [1] "logical"
Variables:
Variables are one of the basic data types in R that store values and are an important
component in R programming, especially for a data scientist. A variable in R data types can
store a number, an object, a statistical result, vector, dataset, a model prediction basically
anything R outputs. We can use that variable later simply by calling the name of the variable.
To declare variable data structures in R, we need to assign a variable name. The name should
not have space. We can use _ to connect to words.
name_of_variable = value
In the command line, we can write the following codes to see what happens:
Example 1:
# Print variable x
x <- 42
Output:
## [1] 42
Example 2:
y <- 10
Output:
## [1] 10
Example 3:
x-y
Output:
## [1] 32
Vectors:
A vector is a one-dimensional array. We can create a vector with all the basic R data types
we learnt before. The simplest way to build vector data structures in R, is to use the c
command.
Example 1:
# Numerical
vec_num
Output:
## [1] 1 10 49
Example 2:
# Character
vec_chr
Output:
Example 3:
# Boolean
vec_bool
Output:
Example 4:
sum_vect
Output:
[1] 3 7 11
Example 5:
In R, it is possible to slice a vector. In some occasion, we are interested in only the first five
rows of a vector. We can use the [1:5] command to extract the value 1 to 5.
slice_vector[1:5]
Output:
## [1] 1 2 3 4 5
Example 6:
The shortest way to create a range of value is to use the: between two numbers. For instance,
from the above example, we can write c(1:10) to create a vector of value from one to ten.
c(1:10)
Output:
## [1] 1 2 3 4 5 6 7 8 9 10
Arithmetic Operators
We will first see the basic arithmetic operators in R data types. Following are the arithmetic
and boolean operators in R programming which stand for:
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
^ or ** Exponentiation
Example 1:
# An addition
3+4
Output:
## [1] 7
You can easily copy and paste the above R code into Rstudio Console. The output is
displayed after the character #. For instance, we write the code print('Guru99') the output will
be ##[1] Guru99.
The ## means we print an output and the number in the square bracket ([1]) is the number of
the display
The sentences starting with # annotation. We can use # inside an R script to add any
comment we want. R won't read it during the running time.
Example 2:
# A multiplication
3*5
Output:
## [1] 15
Example 3:
# A division
(5+5)/2
Output:
## [1] 5
Example 4:
# Exponentiation
2^5
Output:
Example 5:
## [1] 32
# Modulo
28%%6
Output:
## [1] 4
Logical Operators:
With logical operators, we want to return values inside the vector based on logical
conditions. Following is a detailed list of logical operators of data types in R programming
Logical Operators in R
The logical statements in R are wrapped inside the []. We can add many conditional
statements as we like but we need to include them in a parenthesis. We can follow this
structure to create a conditional statement:
variable_name[(conditional_statement)]
With variable_name referring to the variable, we want to use for the statement. We create the
logical statement i.e. variable_name > 0. Finally, we use the square bracket to finalize the
logical statement. Below, an example of a logical statement.
Example 1:
logical_vector>5
Output:
## [1]FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
In the output above, R reads each value and compares it to the statement logical_vector>5. If
the value is strictly superior to five, then the condition is TRUE, otherwise FALSE. R returns
a vector of TRUE and FALSE.
Example 2:
In the example below, we want to extract the values that only meet the condition 'is strictly
superior to five'. For that, we can wrap the condition inside a square bracket precede by the
vector containing the values.
logical_vector[(logical_vector>5)]
Output:
## [1] 6 7 8 9 10
Example 3:
# Print 5 and 6
Output:
## [1] 5 6
Conclusion:
Sample Questions:
1) Describe R Environment.
2) Explain uses of R
3) Explain advantages of R.
4) Describe Data types in R.
5) Explain logical operator in R.
6) Explain variables in R.
EXPERIMENT NO: 07
Title: Implementation of Different Data Structures in R
Aim: To study and implement different data structures in R such as Vectors, Lists, and Data
Frames.
[Link]
A vector is the basic data structure in R. It stores elements of the same data type (numeric,
character, logical, etc.).
In R, a vector is a basic data structure used to store multiple values of the same [Link] is a one-
dimensional data structure and can hold numeric, character, logical, or other atomic types.
In R, To create a vector, we use c() function(combine function) and in this, the elements are
separated by a comma(,).
Syntax:
vect_name<- c(e1,e2,e3,..)
Example:
Filename: VectorEx.R
# Numeric vector
numbers <- c(10, 20, 30, 40)
print("Numeric Vector:")
print(numbers)
# Character vector
subjects <- c("Math", "Science", "History")
print("Character Vector:")
print(subjects)
# Logical vector
flags <- c(TRUE, FALSE, TRUE)
print("Logical Vector:")
print(flags)
Output:
2. Lists
A list is a data structure that can store elements of different data types such as numbers, strings,
vectors, and even data frames.
A list is a collection of elements of different types. Lists are particularly useful when you need to
store heterogeneous data.
In other words, A list is a flexible data structure that can store elements of different types,
including numbers, characters, vectors, matrices, other lists, and even functions.
In R, To create a list, we use list() function and in this, the elements are separated by a comma(,).
Syntax:
list_name<- list(e1,e2,e3,..)
Example:
Filename: ListEx.R
print("List Example:")
print(student)
Output:
$age
[1] 21
$scores
[1] 85 90 95
$pass
[1] TRUE
3. Data Frames
A data frame is a two-dimensional tabular data structure where each column can have a
different data type, but all columns must have the same length.
# Accessing a column
print("Names of students:")
print(students$Names)
Output:
EXPERIMENT NO: 08
Theory:
R – Line Graphs:
A line graph is a chart that is used to display information in the form of a series of data
points. It utilizes points and lines to represent change over time. Line graphs are drawn by
plotting different points on their X coordinates and Y coordinates, then by joining them together
through a line from beginning to end. The graph represents different values as it can move up
and down based on the suitable variable.
R – Line Graphs:
Parameters:
Example:
Output:
Take all parameters which are required to make line chart by giving a title to the chart and add
labels to the axes.
We can add more features by adding more parameters with more colors to the points and lines.
Example:
Output:
In above example, we created line graphs by only one line in each graph.
Example:
Output: When we execute the above code, it shows the following result-
Conclusions:
Sample Questions:
1) Describe Data frame in R.
2) Explain line graph in R.
EXPERIMENT NO: 09
Theory:
R – Bar Charts:
A bar chart is a pictorial representation of data that presents categorical data with
rectangular bars with heights or lengths proportional to the values that they represent. In other
words, it is the pictorial representation of dataset. These data sets contain the numerical values of
variables that represent the length or height.
R uses the function barplot() to create bar charts. Here, both vertical and Horizontal bars can be
drawn.
Syntax:
Parameters:
H: This parameter is a vector or matrix containing numeric values which are used in bar
chart.
xlab: This parameter is the label for x axis in bar chart.
ylab: This parameter is the label for y axis in bar chart.
main: This parameter is the title of the bar chart.
[Link]: This parameter is a vector of names appearing under each bar in bar chart.
col: This parameter is used to give colors to the bars in the graph.
Example:
Output:
Take all parameters which are required to make simple bar chart.
barplot(A, horiz=TRUE )
Output:
Label, title and colors are some properties in the bar chart which can be added to the bar by
adding and passing an argument.
Approach:
X-axis and Y-axis can be labeled in bar chart. To add the label in bar chart.
barplot( A, col=color_name)
Example :
Output:
The bar chart can be represented in two form group of bars and stacked.
Approach:
Take a vector value and make it matrix M which to be grouped or stacked. Making of matrix can
be done by.
barplot( beside=TRUE )
Example 1:
Output:
Example 2:
Output:
Conclusions:
Sample Questions:
1) Describe data visualization in R.
2) Explain bar charts in R.
EXPERIMENT NO: 10
Theory:
R – Pie Charts:
A pie chart is a circular statistical graphic, which is divided into slices to illustrate
numerical proportions. It depicts a special chart that uses “pie slices”, where each sector shows
the relative sizes of data. A circular chart cuts in a form of radii into segments describing relative
frequencies or magnitude also known as a circle graph.
R – Pie Charts:
R Programming Language uses the function pie() to create pie charts. It takes positive numbers
as a vector input.
Parameters:
x: This parameter is a vector that contains the numeric values which are used in the pie
chart.
labels: This parameter gives the description to the slices in pie chart.
radius: This parameter is used to indicate the radius of the circle of the pie chart.(value
between -1 and +1).
main: This parameter is represents title of the pie chart.
clockwise: This parameter contains the logical value which indicates whether the slices
are drawn clockwise or in anti clockwise direction.
col: This parameter give colors to the pie in the graph.
Example:
pie(geeks, labels)
Output:
Take all parameters which are required to make pie chart by giving a title to the chart and add
labels.
We can add more features by adding more parameters with more colors to the points.
Example:
# color pallet.
col = rainbow(length(geeks)))
Output:
To create chart legend and slice percentage, we can plot by doing the below methods.
slice percentage
chart legend.
We can show the chart in the form of percentages as well as add legends.
Example:
Output:
3D Pie Chart:
Here we are going to create a 3D Pie chart using plotrix package and then we will use pie3D()
function to plot 3D plot.
library(plotrix)
Output:
Conclusions:
Sample Questions:
1) Describe data visualization in R.
2) Explain Pie charts in R.
EXPERIMENT NO: 11
Theory:
The measure of central tendency in R Language represents the whole set of data by a single
value. It gives us the location of central points. There are three main measures of central
tendency:
Mean
Median
Mode
Prerequisite:
Before doing any computation, first of all, we need to prepare our data, save our data in external
.txt or .csv files and it’s a best practice to save the file in the current directory. After that import,
your data into R as follow:
myData = [Link]("[Link]",
stringsAsFactors=F)
print(head(myData))
Output:
It is the sum of observations divided by the total number of observations. It is also defined as
average which is the sum divided by count.
Example:
# R program to illustrate
# Descriptive Analysis
myData = [Link]("[Link]",
stringsAsFactors=F)
mean = mean(myData$Age)
print(mean)
Output:
[1] 28.78889
It is the middle value of the data set. It splits the data into two halves. If the number of elements
in the data set is odd then the center element is median and if it is even then the median would be
the average of two central elements.
Example:
# R program to illustrate
# Descriptive Analysis
myData = [Link]("[Link]",
stringsAsFactors=F)
median = median(myData$Age)
print(median)
Output:
[1] 26
It is the value that has the highest frequency in the given data set. The data set may have no
mode if the frequency of all data points is the same. Also, we can have more than one mode if we
encounter two or more data points having the same frequency. There is no inbuilt function for
finding mode in R, so we can create our own function for finding the mode or we can use the
package called modest.
There is no in-built function for finding mode in R. So let’s create a user-defined function that
will return the mode of the data passed. We will be using the table() method for this as it creates
a categorical representation of data with the variable names and the frequency in the form of a
table. We will sort the column Age column in descending order and will return the 1 value from
the sorted values.
myData = [Link]("[Link]",
stringsAsFactors=F)
mode = function(){
return(sort(-table(myData$Age))[1])
mode()
Output:
25: -25
We can use the modest package of the R. This package provides methods to find the mode of the
univariate data and the mode of the usual probability distribution.
Example:
# R program to illustrate
# Descriptive Analysis
library(modest)
myData = [Link]("[Link]",
stringsAsFactors=F)
mode = mfv(myData$Age)
print(mode)
Output:
[1] 25
Conclusions:
Sample Questions:
1) Describe mean, median and mode.
2) Explain measure of central tendency in R.
EXPERIMENT NO: 12
Theory:
R - Linear Regression:
Regression analysis is a very widely used statistical tool to establish a relationship model
between two variables. One of these variable is called predictor variable whose value is gathered
through experiments. The other variable is called response variable whose value is derived from
the predictor variable.
In Linear Regression these two variables are related through an equation, where exponent
(power) of both these variables is 1. Mathematically a linear relationship represents a straight
line when plotted as a graph. A non-linear relationship where the exponent of any variable is not
equal to 1 creates a curve.
y = ax + b
A simple example of regression is predicting weight of a person when his height is known. To do
this we need to have the relationship between height and weight of a person.
Carry out the experiment of gathering a sample of observed values of height and corresponding
weight.
Find the coefficients from the model created and create the mathematical equation using these
Get a summary of the relationship model to know the average error in prediction. Also called
residuals.
Input Data
# Values of height
151, 174, 138, 186, 128, 136, 179, 163, 152, 131
# Values of weight.
lm() Function:
This function creates the relationship model between the predictor and the response variable.
Syntax
lm(formula,data)
Live Demo
x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)
print(relation)
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
-38.4551 0.6746
Live Demo
x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)
print(summary(relation))
Call:
lm(formula = y ~ x)
Residuals:
Coefficients:
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
predict() Function:
Syntax
predict(object, newdata)
object is the formula which is already created using the lm() function.
newdata is the vector containing the new value for predictor variable.
Live Demo
x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)
print(result)
76.22869
x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)
Conclusions:
Sample Questions:
1) Describe linear regression.
2) Explain procedure to perform linear regression in R.