Module 5: DAV with R
R Programming Language - Introduction
R is a programming language designed for statistical computing, data analysis and
visualization. Developed in the early 1990s by Ross Ihaka and Robert Gentleman, it
provides a flexible environment for working with structured and unstructured data. Today,
R is extensively used across data science, academic research, finance and healthcare to
analyze data, build statistical models and support informed decision-making.
Specifically built for statistical analysis and data modeling
Open-source and freely available to everyone
Supported by thousands of packages via the Comprehensive R Archive Network
Why Choose R Programming?
R is a unique language that offers a wide range of features for data analysis, making
it an essential tool for professionals in various fields. Here’s why R is preferred:
Free and Open-Source: R is open to everyone, meaning users can modify, share and
distribute their work freely.
Designed for Data: R is built for data analysis, offering a comprehensive set of tools
for statistical computing and graphics.
Large Package Repository: The Comprehensive R Archive Network (CRAN) offers
thousands of add-on packages for specialized tasks.
Cross-Platform Compatibility: R can work on Windows, Mac and Linux operating
systems.
Great for Visualization: With packages like ggplot2, R makes it easy to create
informative, interactive charts and plots.
Key Features of R
Cross-Platform Support: R works on multiple operating systems, making it versatile
for different environments.
Interactive Development: R allows users to interactively experiment with data and
see the results immediately.
Data Wrangling: Tools like dplyr and tidyr help simplify data cleaning and
transformation.
Statistical Modeling: R has built-in support for various statistical models like
regression, time-series analysis and clustering.
Reproducible Research: With R Markdown, users can combine code, output and
narrative in one document, ensuring their analysis is reproducible.
Example Program in R
To understand how R works, here’s a basic example where we calculate the mean and
standard deviation of a dataset:
We first create a vector data that contains numerical values.
We use the mean() function to calculate the mean of the dataset.
The sd() function calculates the standard deviation.
Output:
[1] "Mean: 27.5"
[1] "Standard Deviation: 15.1382517704875"
Applications of R
R is used in a variety of fields, including:
Data Science and Machine Learning: R is widely used for data analysis, statistical
modeling and machine learning tasks.
Finance: Financial analysts use R for quantitative modeling and risk analysis.
Healthcare: In clinical research, R helps analyze medical data and test hypotheses.
Academia: Researchers and statisticians use R for data analysis and publishing
reproducible research.
Advantages of R Programming
Comprehensive Statistical Tools: R includes many statistical functions and models,
making it the ideal choice for data analysis.
Customizable Visualizations: R’s visualization tools allows for customizations for a
simple bar chart or a detailed heatmap.
Extensive Community Support: R has a large user base and there are countless
resources, forums and tutorials available.
Highly Extendable: The availability of over 15,000 R packages means we can extend
R's functionality to suit any project or need.
Limitations of R Programming
Can consume high memory with very large datasets
Slower execution speed for large-scale computations
Syntax may be challenging for beginners
Error handling is less structured compared to some modern languages
Difference between R Programming and Python Programming
Below are some major differences between R and Python:
Feature R Python
R is a language and
Python is a general-purpose
environment for statistical
programming language for
Introduction programming which
data analysis and scientific
includes statistical
computing
computing and graphics.
It can be used to develop
It has many features which
GUI applications and web
Objective are useful for statistical
applications as well as with
analysis and representation.
embedded systems
It has many easy-to-use It can easily perform matrix
Workability packages for performing computation as well as
tasks optimization
Various popular R IDEs are Various popular Python
Integrated development
Rstudio, RKward, R IDEs are Spyder,
environment
commander, etc. Eclipse+Pydev, Atom, etc.
Some essential packages
There are many packages
and libraries
Libraries and packages and libraries
are Pandas, Numpy, Scipy,
like ggplot2, caret, etc.
etc.
It is mainly used for It takes a more streamlined
Scope complex data analysis in approach for data science
data science. projects.
Data Import and Export In R Programming:
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
1. Reading a Comma-Separated Value(CSV) File
CSV files are a widely used format for tabular data and R offers built-in functions to read
them easily.
Method 1: 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.
Example:
data1 <- [Link]([Link](), header=T)
data1
Method 2: Using [Link]() Function
This function specifies how the dataset is separated, in this case we take sep=", " as an
argument.
Example:
data2 <- [Link]([Link](), header=T, sep=", ")
data2
2. Reading a Tab-Delimited(txt) File
Tab-delimited files are commonly used for data exchange and R supports reading them
with built-in methods.
Method 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.
Example:
data3 <- [Link]([Link](), header=T)
data3
Method 2: Using [Link]() Function
This function specifies how the dataset is separated, in this case we take sep="\t" as the
argument.
Example:
data4 <- [Link]([Link](), header=T, sep="\t")
data4
3. Using R-Studio
Here we are going to import data through R studio with the following steps.
Steps:
From the Environment tab click on the Import Dataset Menu.
Importing Data in R Script
Select the file extension from the option.
Importing Data in R Script
In the third step, a pop-up box will appear, either enter the file name or browse the
desktop.
The selected file will be displayed on a new window with its dimensions.
In order to see the output on the console, type the filename.
4. Reading JSON Files in R
In order to work with JSON files in R, one needs to install the “rjson” package.
fromJSON(): This function reads and parses a JSON file into an R object.
JSON file for demonstration:
{
"ID":["1","2","3","4","5"],
"Name":["Mithuna","Tanushree","Parnasha","Arjun","Pankaj"],
"Salary":["722.5","815.2","1611","2829","843.25"],
"StartDate":
["6/17/2014","1/1/2012","11/15/2014","9/23/2013","5/21/2013"],
"Dept":["IT","IT","HR","Operations","Finance"]
}
library("rjson")
result <- fromJSON(file = "/content/[Link]")
print(result)
Output:
The output shows the JSON data successfully read into R, with fields such as ID, Name,
Salary, StartDate and Dept stored as vectors. This data can now be converted into a data
frame for further analysis or manipulation.
Exporting data file
Write a file:
[Link](health, "[Link]", [Link] = FALSE)
As before, in order to read data faster, we can use different packages.
Use readr to export .csv files. About twice as fast as [Link] and never exports
row names.
write_csv(health, '[Link]')
Use the package to export SPSS or Stata files
write_spss(health, "my_spss.sav")write_dta(health, "my_stata.dta")