UNIT 1
OVERVIEW OF R:
R is popular programming language used for statistical computing and graphical
representation and reporting.
It’s most common use is to analyse and visualize data.
R was created by ROSS IHAKA and ROBERT GENTLEMEN in 1993.
Both their names start with R that’s the reason to name the programming language as
R.
Before R, S is a programming language used for statistical computing R is
implementation of S.
It is a great resource for data analysis, data visualization, data science and machine
learning.
Data analysis is a process of transforming and modelling data with goal of
discovering useful information and support decision making.
Data visualization is a process of translating information into visual context such as
maps or graphs which makes the data easier to understand.
Data science is a combination of programming skills, mathematics and statistics to
extract meaningful insights from the data.
Machine Learning is a branch of AI which focuses on use of data and algorithms to
imitate the way that human learn.
It provides many statistical techniques(such as statistical tests, classification,
clustering and data reduction)
It is easy to draw graphs in R like pie charts, histograms, box plot, and scatter plot.
It works on different platforms (windows , Mac, Linux)
It is open source and free.
It has a large community of users and developers. This community provides support
various platforms like Stack Overflow, GitHub , and the official R community website
R has a rich set of tools and infrastructure for package development. These packages
can be used to solve different problems.
It provides a suite of operators for calculations on arrays ,lists ,vectors and matrices
R was created at the Department of statistics at the University of Auckland, New
Zealand.
R, the programming language, was heavily influenced by the S language and was
designed to be a free and open-source alternative.
The S language was developed by John Chambers, Rick Becker, and Allan Wilks
in Bell Labs.
R was conceived in [Link], R was called “R-Project” and was designed as a
teaching tool for statistical computing.
The first version of R, version 0.49, was released in [Link] early version of R was
used by Ihka and gentleman’s students.
In 1997, R was officially released as an open-source [Link] the period, R
gained popularity and started to attract a community of users and contributors.
In 2000,R version 1.0.0 was released. In 2004, R was officially recognized as a major
statistical computing platform by the American Statistical Association.
In 2009, R version 2.10.0 was released.
The current version of R 4.4.2 also known as “Pile of Leaves”. Released on October
31, 2024.
R is an Interpreted language.
Defining the R Project:
1. Start R Studio
• To start working with R, need to launch RStudio, which is a powerful
integrated development environment (IDE) for R. Download RStudio from
their official website.
[Link] a new R project
• In R Studio, create a new R project by going to `File > New Project. Choose
either 'New Directory' or 'Existing Directory'. This will create a new R
project and automatically set the working directory.
3. Set the working directory
• Alternatively, set the working directory using the 'setwd()` function in R.
• For example:
• setwd(“C:/users/username/Desktop/MyProject/DatFolder”)
• 4. Save the Project
• To save project in R Studio, go to 'File > Save' to save the current script that is
working on. This will allow to revisit and re-run the project later on.
Obtaining R:
• 1. R Installation: To install R, go to Comprehensive R Archive Network
(CRAN) website. [Link].
• 2. Depending on the operating system, click Download R for (operating
system).
• 3. Click on install R for the first time.
• 4. Click Download R for Windows. Open the downloaded file.
• 5. Select the language would like to use during the installation. Then click OK.
• 6. Click Next.
• 7. Then choose which installation would like.
• 8. If computer is a 64-bit, choose the 64-bit User Installation. Then click next.
• 9. Then specify if want to customized startup or just use the defaults. Then click
next.
• 10. Then choose the folder where R to be saved within or the default if the R
folder that was created. Once have finished, click next.
• 11. Then select additional shortcuts if need. Click Next.
• 12. Click Finish.
• 13. Next, download R Studio. Go to [Link]
• 14. Click Download R studio.
• 15. Click Download under RStudio Desktop- Open Source License.
• 16. Click on the operating system
• 17. The RStudio installation wizard will pop-up. Click Next and go through the
installation steps.
GENERATING R CODE AND SCRIPTS:
Generating R code:
R Studio is an integrated development environment (IDE) for R.
IDE is a GUI, where users can write their code, see the results and also
see the variables that are generated during the course of programming.
R is available as an Open Source software for Client as well as Server
Versions
Creating an R file :
There are two ways to create an R file in R studio:
1. On click the File tab, from there when user click it will give a drop-down menu,
where user can select the new file and then R script, so that, user will get a new file
open.
2. Use the plus button, which is just below the file tab and choose R script, from
there, to open a new R script file.
• Once R script file opened, the following picture shows how an R Studio with
the script file open looks like.
• So, 3 panel’s console, environment/history and file/plots panels are there. On
top left user have a new window, which is now being opened as a script file.
SCRIPTS:
R Studio comes with many built-in features that make it easy to work with
scripts. Users can automatically execute a line of code in a script by clicking the Run
button.
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.
1. Using the run command:
This “run” command can be executed using the GUI, by pressing the run button
there, or users can use the Shortcut key control + enter.
2. Using the source command:
This “source” command can be executed using the GUI, by pressing the source
button there, or users can use the Shortcut key control + shift + S.
3. 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 users can use the Shortcut key control + shift +
enter.
1. The run command will execute the line in which the cursor is there.
2. By using source without echo, it runs the script without displaying the code
in the console.
3. On the other hand, by using source with echo, it not only runs the script but
also prints the code to the console as it executes.
COMMENTS AND TEXT EDITORS FOR R
COMMENTS:
Comments are text added to the code to provide explanations, notes or
documentation. They are ignored by the R interpreter and do not affect the
execution of the code.
In R programming there is only single-line comments. R doesn’t support multi-
line comment.
Purpose of Comments:
Explanation of the code
Prevent execution of code
Document functions
Code readability
Types of Comments:
1. Single –Line Comments
2. Multi-Line Comments
[Link]-Line Comments:
• Single-Line Comments are comments that require only one line. Just like
python Single-Line comments, any statement starting with ‘#” is a
comment in R.
Syntax: # Comment Statement
Examples:
1. #Declare variable
Age=24
2.#This code prints Hello World
Print (“HELLO WORLD”)
Output: hello world
3. #A Number
Marks<-96
#Display the marks
Marks
Output:96
4.R program to add two numbers
#Assigning values to variables
A<-9
B<-4
#printing sum
Print(A+B)
Output: 13
5. This is single line comments
X<-5 #Assign 5 to x
[Link]-Line Comments:
• R does not have any syntax to create multi-Line comments.
• In R Programming language multi-Line comments are created using the #
symbol at the beginning of each line.
• As stated earlier that R doesn’t support multi-lined comments, but to make
the commenting process easier, R allows commenting on multiple single
lines at once.
• Example:
# This is a multiple-line comment
# Each line starts with the '#' symbol
# The following code will be executed
x <- 10
y <- 20
sum <- x + y
print(sum) # This line will print the value of 'sum'
FIRST WAY:
• Select the multiple lines on which you want to comment using the cursor
and then use the key combination “control + shift + C” to comment or
uncomment the selected lines.
SECOND WAY:
The other way is to use the GUI, select the lines on which you want to
comment by using the cursor and click on “Code” in the menu, a pop-up window
pops out in which we need to select “Comment/Uncomment Lines” which
appropriately comments or uncomment the lines which you have selected.
TEXT EDITORS:
In R programming, text editors are essential for writing, editing, and
managing R scripts and programs. Text editors can range from basic editors like
Notepad to advanced Integrated Development Environments (IDEs) tailored
specifically for R.
1. RStudio:
Description: RStudio is the most popular IDE for R programming. It provides
a comprehensive environment for writing R code, debugging, and visualization.
Features:
• Syntax highlighting and auto-completion.
• Integrated R console for immediate code execution.
• Tools for data visualization and plotting.
• Version control integration (e.g., Git).
[Link]++:
Description: A lightweight text editor for Windows with support for multiple
programming languages, including R.
Features:
• Syntax highlighting for R scripts.
• Customizable interface and plugins.
• Lightweight and fast.
[Link] Studio Code (VS Code):
Description: A highly versatile code editor that supports R programming
through extensions like the R Extension for Visual Studio Code.
Features:
• Syntax highlighting, debugging, and IntelliSense.
• Extensions for R language support.
• Terminal integration for running R scripts directly.
• Customizable themes and extensions for broader language support.
4 .Sublime Text:
Overview: Sublime Text is a feature-rich text editor with syntax highlighting
and code completion.
Features:
• Syntax highlighting and code completion
• Code folding and navigation
• Customizable with plugins
• Support for multiple programming languages
[Link]:
Overview: TextMate is a popular text editor for macOS with R support.
Features:
• Syntax highlighting and code completion
• Code folding and navigation
Customizable with bundles
[Link]:
Overview: Atom is a customizable text editor with R support through packages.
Features:
• Syntax highlighting and code completion
• Code folding and navigation
• Customizable with packages
• Support for multiple programming languages
[Link] (ESS - Emacs Speaks Statistics):
Description: Emacs is a powerful text editor, and its ESS mode is tailored for
statistical programming, including R.
Features:
• Syntax Highlighting - including R, S, SAS.
• Code Completion - making it easier to write code.
• Debugging - to help users identify and fix errors.
Graphical user interface(GUIs) for R, Packages
GUIs for R
• Since R was first launched, it has managed to gain the support of an ever-increasing
percentage of academic and professional statisticians.
• However, the spread of its use among novice and occasional users of statistics have
not progressed at the same pace, which can be attributed partially to the lack of a
graphical user interface (GUI).
• Nevertheless, this situation has changed in the last years and there is currently several
projects that have added GUIs to R.
• A graphical user interface (GUI) in R programming refers to a visual interface that
allows users to interact (with R through graphical elements such as buttons, menus,
and windows.
• While R is primarily a command-line-driven language, Guis provide a more user-
friendly way to execute R code and perform data analysis tasks. Some popular GUIs
for R programming include R Studio, Jupyter Notebook with R kernel, and RK Ward.
• One popular R GUI is R Studio. It offers a point-and-click interface for managing
scripts, viewing data, and plotting graphs. Users can execute R code by interacting
with the GUI elements, making it more accessible for those less familiar with
command-line interfaces.
• Jupyter Notebooks with R kernel, providing an interactive environment where users
can combine code, visualizations, and explanatory text in a document- style format.
• RK Ward is a KDE-based GUI for R programming that offers features such as syntax
highlighting, code completion, integrated help, data import/export, data manipulation,
and visualization.
• Syntax Highlighting: Different parts of the code might be highlighted in different
colors to make it easier to read and understand.
• Code completion: RStudio supports the automatic completion of code using the Tab
key. For example, if an object named pollResults exists in the workspace, typing poll
in the R console and then pressing the Tab key automatically completes the full name
of the object.
• Integrated Help: If not sure how to use a function or need information about R
commands, RK Ward can provide help and explanations right there in the program
• Data Import/Export: It helps to bring data from external sources or export the results
to other formats.
• Data Manipulation: Can perform operations on data, like sorting, filtering try it
directly within RK Ward.
• Visualization: It offers tools for creating charts and graphs to visualize the data.
• There are several different options available in R to produce graphical user interfaces
(GUIs); we are going to focus on a simple, portable one based on the Tcl/Tk library
originally developed by John Ousterhout.
• Tcl/Tk is a combination of a scripting language and a toolkit for GUI.
• Since version 1.1.0, R has had a tcltk packages to access the Tk tootlkit, replacing Tcl
code with R function calls.
• Tcl is a scripting language (like perl or python)
• Tk is a graphical toolkit designed to work with that language.
• Since the Tk toolkit is portable, easy-to-use, and provides most of the basic elements
needed to create GUIs, interfaces to it are available in many languages.
• To use the Tcl/Tk library in R, you must load the library with
the library(tcltk) command.
• This library is part of the base R distribution, so you don't have to download anything
in order to use it.
• The process of creating a GUI can be broken down into two parts: choosing the
elements (often referred to as widgets) that will make up the GUI, and arranging for
the elements to be placed in the appropriate positions and displayed.
• This second step is sometimes known as geometry management. Tk actually offers
several different geometry management methods; we are going to focus on one known
as packing.
• In the packing geometry model, the GUI is considered a collection of separate frames,
each containing some of the widgets that make up the final GUI. The widgets are
loaded into the frames in a carefully chosen order, and they "spread out" to fill the
frame. When you pack a widget into a frame, you can specify the side to which to
pack it, choosing among left, right, top or bottom.
• Most of the widgets that are available through the Tk toolbox should look familiar, as
common applications like email clients and web browser use these same elements in
their GUIs.
Here are some benefits of using a GUI in R:
• Ease of use
GUIs make it easier to use R, especially for people who don't have the time to become
experienced programmers.
• Generate code
GUIs generate R code on the fly, which you can then access and save to run directly
on the R command line.
• Help
Most R GUIs provide help on the dialog box settings, custom functions, and R
functions used by the custom functions.
• Simplicity
GUls can be useful when you want to develop an R program that others can run by
specifying a file and choosing a few options.
Packages
Packages
• Packages are a way to organize related classes and interfaces in a programming
language, and are similar to folders on a computer.
• Purpose: Packages are used to:
Avoid name conflicts
Write more maintainable code
Reuse code
Provide access protection
Manage namespace
R Packages:
• Perhaps the biggest reason for R's phenomenally ascendant popularity is its collection
of user contributed packages. As of early February 2017 there were over 10,000
packages available on CRAN¹ written by more than 2,000 different people.
• Odds are good that if a statistical technique exists, it has been written in R and
contributed to CRAN. Not only is there an incredibly large number of packages; many
are written by the authorities in the field, such as Andrew Gelman, Trevor Hastie, Dirk
Eddelbuettel and Hadley Wickham.
• A package is essentially a library of prewritten code designed to accomplish some task
or a collection of tasks.
• The survival package is used for survival analysis, ggplot2 is used for plotting and sp
is for dealing with spatial data. It is important to remember that not all packages are of
the same quality.
• This book will not attempt to be an exhaustive list of good packages to use, because
that is constantly changing. However, there are some packages that are so pervasive
that they will be used in this book as if they were part of base R.
• Some of these are ggplot2, tidyr and dplyr by Hadley Wickham; glmnet by Trevor
Hastie, Robert Tibshirani and Jerome Friedman; Repp by Dirk Eddelbuettel and knitr
by Yihui Xie. We have written a package on CRAN, coefplot, useful and resumer with
more to follow.
Installing Packages
• As with many tasks in R, there are multiple ways to install packages. The simplest is
to install them using the GUI provided by RStudio and shown in Figure 3.1. Access
the Packages pane shown in this figure either by clicking its tab or by pressing Ctrl+7
on the keyboard.
From here simply type the name of a package (RStudio has a nice autocomplete
feature for this) and click Install. Multiple packages can be specified, separated by
commas.
• This downloads and installs the desired package, which is then available for use.
• Selecting the Install dependencies checkbox will automatically download and install
all packages that the desired package requires to work.
• For example, our coefplot package depends on ggplot2, plyr, dplyr, useful, stringr and
reshape2, and each of those may have further dependencies.
• An alternative is to type a very simple command into the console:
> [Link] ("coefplot")
This will accomplish the same thing as working in the GUI.
• There has been a movement recently to install packages directly from GitHub or
BitBucket repositories, especially to get the development versions of packages. This
can be accomplished using devtools.
> library (devtools)
>install github (repo="coefplot/jaredlander")
• In order to use functions in the devtools package we first needed to load the package
using library.
• If the package being installed from a repository contains source code for a compiled
language generally C++ or FORTRAN then the proper compilers must be installed.
• Sometimes there is a need to install a package from a local file, either a zip of a
prebuilt package or a [Link] of package code.
• This can be done using the installation dialog mentioned before but switching the
Install from: option to Package Archive File.
• Then browse to the file and install. Note that this will not install dependencies, and if
they are not present, the installation will fail. Be sure to install dependencies first.
• Similarly to before, this can be accomplished using [Link].
> [Link]("coefplot _1.[Link]")
Uninstalling Packages
• In the rare instance when a package needs to be uninstalled, it is easiest to click the
white X inside a gray circle on the right of the package descriptions in RStudio's
Packages pane.
• Alternatively, this can be done with [Link], where the first argument is a
character vector naming the packages to be removed.
Loading Packages
• Now that packages are installed they are almost ready to use and just need to be
loaded first. There are two commands that can be used, either library or require.
• They both accomplish the same thing: Loading the package. Using require will return
TRUE if it succeeds and FALSE with a warning if it cannot find the package.
• This returned value is useful when loading a package from within a function, a
practice considered acceptable to some, improper to others.
• Calling library on a package that is not installed will cause an error which can be
advantageous when running code in scripts.
• In interactive usage there is not much of a difference but is preferable, when writing
scripts, to use library.
• The argument to either function is the name of the desired package, with or without
quotes.
• So loading the coefplot package would look like:
> library (coefplot)
Loading required package: ggplot2
• It also prints out the dependent packages that get loaded as well. This can be
suppressed by setting the argument quietly to TRUE.
> library (coefplot, quietly=TRUE)
• A package only needs to be loaded when starting a new R session. Once loaded, it
remains available until either R is restarted or the package is unloaded.
• An alternative to loading a package through code is to select the checkbox next to the
Package name in RStudio's Packages pane. This will load the package by running the
code just shown.
Unloading Packages
• Sometimes a package needs to be unloaded. This is simple enough either by clearing
the checkbox in RStudio's Packages pane or by using detach function.
• The function takes the package name preceded by package: all in quotes.
> detach ("package:coefplot")
• It is not uncommon for functions in different packages to have the same name. For
example, coefplot is in both arm (by Andrew Gelman) and coefplot^2. If both
packages are loaded, the function in the package loaded last will be invoked when
calling that function.
• A way around this is to precede the function with the name of the package, separated
by two colons (::).
> arm::coefplot (object)
>coefplot::coefplot(object)
• Not only does this call the appropriate function; it also allows the function to be called
without even loading the package beforehand.
Building a Package
• Building a package is one of the more rewarding parts of working with R, especially
sharing that package with the community through CRAN.
Updating R and its packages
• The R Core Development Team continuously hones the R language by catching bugs,
improving performance, and updating R to work with new technologies.
• As a result, new versions of R are released several times a year. The easiest way to
stay current with R is to periodically check the CRAN website.
• The website is updated for each new release and makes the release available for
download. User have to install the new release.
• Package authors occasionally release new versions of their packages to add functions,
fix bugs, or improve performance.
• The [Link] command checks whether you have the most current version of a
package and installs the most current version if you do not.
• The syntax for [Link] follows that of [Link]. If you already have
ggplot2, reshape2, and dplyr on your computer, it'd be a good idea to check for
updates before you use them:
[Link](c("ggplot2", "reshape2", "dplyr"))
• You should start a new R session after updating packages. If you have a package
loaded when you update it, you'll have to close your R session and open a new one to
begin using the updated version of the package.
What are Repositories?
• A repository is a place where packages are located and stored so you can install R
packages from it. Organizations and Developers have a local repository, typically they
are online and accessible to everyone. Some of the most popular repositories for R
packages are:
• CRAN: Comprehensive R Archive Network(CRAN) is the official repository, it is a
network of FTP and web servers maintained by the R community around the world.
The R community coordinates it, and for a package to be published in CRAN, the
Package needs to pass several tests to ensure that the package is following CRAN
policies.
• Bioconductor: Bioconductor is a topic-specific repository, intended for open source
software for bioinformatics. Similar to CRAN, it has its own submission and review
processes, and its community is very active having several conferences and meetings
per year in order to maintain quality.
• Github: Github is the most popular repository for open-source projects. It’s popular as
it comes from the unlimited space for open source, the integration with git, a version
control software, and its ease to share and collaborate with others.
List of R packages
• tidyr:
The word tidyr comes from the word tidy, which means clear. So the tidyr package is
used to make the data tidy.
• ggplot2:
R allows us to create graphics declaratively. R provides the ggplot2 package for this
purpose. This package is famous for its elegant and quality graphs which sets it apart
from other visualization packages.
• dplyr:
R allows us to perform data wrangling and data analysis. R provides the dplyr library
for this purpose. This library facilitates several functions for the data frame in R.
• reshape2:
This package facilitates flexible reorganization and aggregation of data using melt()
and decast() function.
• digest:
The digest package is used for the creation of cryptographic hash objects of R
functions.
• leaflet
For creating interactive visualization, R provides the leaflet package. This package is
an open-source JavaScript library. The world's popular websites like the New York
Times, Github and Flicker, etc. are using leaflet. The leaflet package makes it easier to
interact with these sites.
• ggmap
For delineating spatial visualization, the ggmap package is used. It is a mapping
package which consists of various tools for geolocating and routing.
• glue
R provides the glue package to perform the operations of data wrangling. This
package is used for evaluating R expressions which are present within the string.
• shiny
R allows us to develop interactive and aesthetically pleasing web apps by providing
a shiny package. This package provides various extensions with HTML widgets, CSS,
and JavaScript.
• plotly
The plotly package provides online interactive and quality graphs. This package
extends upon the JavaScript library -[Link].
• tidytext
The tidytext package provides various functions of text mining for word
processing and carrying out analysis through ggplot, dplyr, and other miscellaneous tools.
• stringr
The stringr package provides simplicity and consistency to use wrappers for the
'stringi' package. The stringi package facilitates common string operations.
• Dichromat
The R dichromat package is used to remove Red-Green or Blue-Green contrasts from
the colors.
• MASS
The MASS package provides a large number of statistical functions. It provides
datasets that are in conjunction with the book "Modern Applied Statistics with S."
• caret
R allows us to perform classification and regression tasks by providing the caret
package. CaretEnsemble is a feature of caret which is used for the combination of
different models.
e1071
The e1071 library provides useful functions which are essential for data analysis like
Naive Bayes, Fourier Transforms, SVMs, Clustering, and other miscellaneous functions.
sentimentr
The sentiment package provides functions for carrying out sentiment analysis. It is used
to calculate text polarity at the sentence level and to perform aggregation by rows or
grouping variables.
ggraph
R provides an extension of ggplot known as ggraph. The limitation of ggplot is the
dependency on tabular data is taken away in ggraph.
tidyquant
The tidyquant is a financial package which is used for carrying out quantitative
financial analysis. This package adds to the tidyverse universe as a financial package
which is used for importing, analyzing and visualizing the data.
dygraphs
The dygraphs package provides an interface to the main JavaScript library which we
can use for charting. This package is essentially used for plotting time-series data in R.
Why develop an R package?
• The reasons of creating R package can be categorized into four categories such as:
• Reuse: Package your functions and datasets for use across multiple projects.
• Distribution: share your code with colleagues or the broader R community.
• Organization: Keep your code modular and well-organized.
• Version control: Track changes and maintain different versions of your package.
Conclusion
• Packages make up the backbone of the R community and experience. They are often
considered what makes working with R so desirable. This is how the community
makes its work, and so many of the statistical techniques, available to the world.
• With such a large number of packages, finding the right one can be overwhelming.
CRAN Task Views ([Link] offers a curated listing of
packages for different needs.