0% found this document useful (0 votes)
6 views40 pages

Comp Statistics Using R

The document provides an overview of the application of statistics in various fields such as business, social sciences, healthcare, and more, highlighting its importance in decision-making. It also details the installation process for R and RStudio, along with the advantages and disadvantages of using R for statistical analysis. Additionally, it outlines the use of R packages, including popular ones like ggplot2 and dplyr, which enhance data analysis and visualization capabilities.

Uploaded by

artirajput2370
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views40 pages

Comp Statistics Using R

The document provides an overview of the application of statistics in various fields such as business, social sciences, healthcare, and more, highlighting its importance in decision-making. It also details the installation process for R and RStudio, along with the advantages and disadvantages of using R for statistical analysis. Additionally, it outlines the use of R packages, including popular ones like ggplot2 and dplyr, which enhance data analysis and visualization capabilities.

Uploaded by

artirajput2370
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

Computa onal Sta cs Using R :

Statistics is a branch of mathematics that deals with the collection, analysis, interpretation,
presentation, and organization of data. It plays a vital role in various fields by providing valuable
insights and facilitating informed decision-making. Let's explore how statistics is applied in
different domains:

1. Business and Economics: In business and economics, statistics is used for market
research, forecasting sales, analyzing financial data, and making informed decisions about
investments. Statistical techniques like regression analysis help identify the relationship
between variables, enabling businesses to optimize their strategies and improve
efficiency.
2. Social Sciences: In fields like sociology, psychology, and anthropology, statistics helps
researchers study human behavior, attitudes, and trends. Surveys and experiments use
statistical methods to draw conclusions from data and test hypotheses. Statistical analysis
helps in understanding social phenomena and making evidence-based policy decisions.
3. Medicine and Healthcare: In the medical field, statistics is used in clinical trials to assess
the effectiveness of new treatments and drugs. Epidemiologists use statistical methods to
study disease patterns and risk factors in populations. Medical researchers also use
statistics to analyze patient data and draw conclusions about health outcomes.
4. Environmental Science: Environmental scientists use statistics to analyze data related to
climate change, pollution, and biodiversity. They study trends and patterns in
environmental data to understand the impact of human activities on the planet and
develop strategies for sustainable resource management.
5. Education: In the field of education, statistics is used to analyze test scores, evaluate
educational programs, and identify areas for improvement in teaching methods.
Researchers use statistical techniques to measure student performance and assess the
effectiveness of educational interventions.
6. Government and Public Policy: Governments use statistics to collect and analyze data
on demographics, economy, and public health. This information is crucial for policy
development and resource allocation. Census data and surveys help governments plan
and implement social and economic programs.
7. Sports Analytics: In sports, statistics are used to analyze player performance, team
strategies, and game outcomes. Sports analytics has become increasingly popular in
recent years, enabling teams to make data-driven decisions regarding player selection,
tactics, and training.
8. Quality Control and Manufacturing: Industries employ statistical quality control to
monitor and improve the production process. Statistical methods like Six Sigma help
identify and reduce defects, ensuring that products meet high-quality standards.
9. Market Research and Polling: Statistics is essential in market research to analyze
consumer behavior, preferences, and market trends. Polling organizations use statistical
sampling techniques to estimate public opinion on various issues.
10. Finance and Investment: In finance, statistics is used to analyze stock market data,
manage investment portfolios, and assess risk. Financial analysts use statistical models to
make predictions and guide investment decisions.

[Notes by : Deshmukh D.R.]


2

Installation of R
R programming is a very popular language and to work on that we have to install two
things, i.e., R and RStudio. R and RStudio works together to create a project on R.

The official site [Link] provides binary files for major operating
systems including Windows, Linux, and Mac OS. In some Linux distributions, R is
installed by default, which we can verify from the console by entering R.

Install R in Windows
There are following steps used to install the R in Windows:

Step 1:

First, we have to download the R setup from [Link]


[Link]/bin/windows/base/.

Step 2:

When we click on Download R 3.6.1 for windows, our downloading will be started
of R setup. Once the downloading is finished, we have to run the setup of R in the
following way:

1) Select the path where we want to download the R and proceed to Next.

[Notes by : Deshmukh D.R.]


3

2) Select all components which we want to install, and then we will proceed to Next.

3) In the next step, we have to select either customized startup or accept the default,
and then we proceed to Next.

[Notes by : Deshmukh D.R.]


4

4) When we proceed to next, our installation of R in our system will get started:

5) In the last, we will click on finish to successfully install R in our system.

[Notes by : Deshmukh D.R.]


5

RStudio IDE
RStudio is an integrated development environment which allows us to interact with R
more readily. RStudio is similar to the standard RGui, but it is considered more user-
friendly. This IDE has various drop-down menus, Windows with multiple tabs, and so
many customization processes. The first time when we open RStudio, we will see three
Windows. The fourth Window will be hidden by default. We can open this hidden
Window by clicking the File drop-down menu, then New File and then R Script.

RStudio Loca on Descrip on


Windows/Tabs

Console Window Lower-left The location where commands are entered and
output is printed.

Source Tabs Upper-left Built-in test editor

Environment Tab Upper-left An interactive list of loaded R objects.

History Tab Upper-left List of keystrokes entered into the console.

Files Tab Lower-right File explorer to navigate C drive folders.

Plots Tab Lower-right Output location for plots.

Packages Tab Lower-right List of installed packages.

Help Tab Lower-right Output location for help commands and help
search Window.

[Notes by : Deshmukh D.R.]


6

Viewer Tab Lower-right Advanced tab for local web content.

Installation of RStudio

Installation on Windows/Linux
On Windows and Linux, it is quite simple to install RStudio. The process of installing
RStudio in both the OS is the same. There are the following steps to install RStudio in
our Windows/Linux:

Step 1:0s

In the first step, we visit the RStudio official site and click on Download RStudio.

Step 2:

In the next step, we will select the RStudio desktop for open-source license and click
on download.

[Notes by : Deshmukh D.R.]


7

Step 3:

In the next step, we will select the appropriate installer. When we select the installer,
our downloading of RStudion setup will start.

[Notes by : Deshmukh D.R.]


8

Step 4:

In the next step, we will run our setup in the following way:

1) Click on Next.

2) Click on Install.

[Notes by : Deshmukh D.R.]


9

3) Click on finish.

[Notes by : Deshmukh D.R.]


10

4) RStudio is ready to work.

R Advantages and Disadvantages


R is the most popular programming language for statistical modeling and analysis.
Like other programming languages, R also has some advantages and disadvantages.
It is a continuously evolving language which means that many cons will slowly fade
away with future updates to R.

There are the following pros and cons of R

[Notes by : Deshmukh D.R.]


11

Pros
1) Open Source
An open-source language is a language on which we can work without any need for a
license or a fee. R is an open-source language. We can contribute to the development
of R by optimizing our packages, developing new ones, and resolving issues.

2) Platform Independent
R is a platform-independent language or cross-platform programming language
which means its code can run on all operating systems. R enables programmers to
develop software for several competing platforms by writing a program only once. R
can run quite easily on Windows, Linux, and Mac.

3) Machine Learning Operations


R allows us to do various machine learning operations such as classification and
regression. For this purpose, R provides various packages and features for developing
the artificial neural network. R is used by the best data scientists in the world.

4) Exemplary support for data wrangling


R allows us to perform data wrangling. R provides packages such as dplyr, readr which
are capable of transforming messy data into a structured form.

5) Quality plotting and graphing


R simplifies quality plotting and graphing. R libraries such as ggplot2 and plotly
advocates for visually appealing and aesthetic graphs which set R apart from other
programming languages.

6) The array of packages


R has a rich set of packages. R has over 10,000 packages in the CRAN repository which
are constantly growing. R provides packages for data science and machine learning
operations.

7) Statistics
R is mainly known as the language of statistics. It is the main reason why R is
predominant than other programming languages for the development of statistical
tools.

[Notes by : Deshmukh D.R.]


12

8) Continuously Growing
R is a constantly evolving programming language. Constantly evolving means when
something evolves, it changes or develops over time, like our taste in music and
clothes, which evolve as we get older. R is a state of the art which provides updates
whenever any new feature is added.

Cons
1) Data Handling
In R, objects are stored in physical memory. It is in contrast with other programming
languages like Python. R utilizes more memory as compared to Python. It requires the
entire data in one single place which is in the memory. It is not an ideal option when
we deal with Big Data.

2) Basic Security
R lacks basic security. It is an essential part of most programming languages such as
Python. Because of this, there are many restrictions with R as it cannot be embedded
in a web-application.

3) Complicated Language
R is a very complicated language, and it has a steep learning curve. The people who
don't have prior knowledge or programming experience may find it difficult to learn
R.

4) Weak Origin
The main disadvantage of R is, it does not have support for dynamic or 3D graphics.
The reason behind this is its origin. It shares its origin with a much older programming
language "S."

5) Lesser Speed
R programming language is much slower than other programming languages such as
MATLAB and Python. In comparison to other programming language, R packages are
much slower.

In R, algorithms are spread across different packages. The programmers who have no
prior knowledge of packages may find it difficult to implement algorithms.

[Notes by : Deshmukh D.R.]


13

R Packages
R packages are the collection of R functions, sample data, and compile codes. In the R
environment, these packages are stored under a directory called "library." During
installation, R installs a set of packages. We can add packages later when they are
needed for some specific purpose. Only the default packages will be available when
we start the R console. Other packages which are already installed will be loaded
explicitly to be used by the R program.

There is the following list of commands to be used to check, verify, and use the R
packages.

Check Available R Packages


To check the available R Packages, we have to find the library location in which R
packages are contained. R provides libPaths() function to find the library locations.

1. libPaths()

When the above code executes, it produces the following project, which may vary
depending on the local settings of our PCs & Laptops.

Pip 10s
[1] "C:/Users/ajeet/OneDrive/Documents/R/win-library/3.6"
[2] "C:/Program Files/R/R-3.6.1/library"

[Notes by : Deshmukh D.R.]


14

Getting the list of all the packages installed


R provides library() function, which allows us to get the list of all the installed packages.

1. library()

When we execute the above function, it produces the following result, which may vary
depending on the local settings of our PCs or laptops.

Packages in library 'C:/Program Files/R/R-3.6.1/library':

Like library() function, R provides search() function to get all packages currently loaded
in the R environment.

1. search()

When we execute the above code, it will produce the following result, which may vary
depending on the local settings of our PCs and laptops:

[1] ".GlobalEnv" "package:stats" "package:graphics"


[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"

Install a New Package


In R, there are two techniques to add new R packages. The first technique is installing
package directly from the CRAN directory, and the second one is to install it manually
after downloading the package to our local system.

[Notes by : Deshmukh D.R.]


15

Install directly from CRAN

The following command is used to get the packages directly from CRAN webpage and
install the package in the R environment. We may be prompted to choose the nearest
mirror. Choose the one appropriate to our location.

1. [Link]("Package Name")
The syntax of installing XML package is as follows:
1. [Link]("XML")

Output

Install package manually

To install a package manually, we first have to download it from [Link]


[Link]/web/packages/available_packages_by_name.html. The required package
will be saved as a .zip file in a suitable location in the local system.

Once the downloading has finished, we will use the following command:

[Notes by : Deshmukh D.R.]


16

1. [Link](file_name_with_path, repos = NULL, type = "source")

Install the package named "XML"

1. [Link]("C:\Users\ajeet\OneDrive\Desktop\graphics\xml2_1.[Link]", re
pos = NULL, type = "source")

Load Package to Library


We cannot use the package in our code until it will not be loaded into the current R
environment. We also need to load a package which is already installed previously but
not available in the current environment.

There is the following command to load a package:

1. library("package Name", [Link] = "path to library")

Command to load the XML package

1. [Link]("C:\Users\ajeet\OneDrive\Desktop\graphics\xml2_1.[Link]", re
pos = NULL, type = "source")

List of R packages
R is the language of data science which includes a vast repository of packages. These
packages appeal to different regions which use R for their data purposes. CRAN has
10,000 packages, making it an ocean of superlative statistical work. There are lots of
packages in R, but we will discuss the important one.

There are some mostly used and popular packages which are as follows:

1) tidyr
The word tidyr comes from the word tidy, which means clear. So the tidyr package is
used to make the data' tidy'. This package works well with dplyr. This package is an
evolution of the reshape2 package.

2) ggplot2
R allows us to create graphics declaratively. R provides the ggplot package for this
purpose. This package is famous for its elegant and quality graphs which sets it apart
from other visualization packages. 10s

[Notes by : Deshmukh D.R.]


17

3) 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.

4) 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.

5) 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.

6) 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.

7) 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.

8) ggmap
For delineating spatial visualization, the ggmap package is used. It is a mapping
package which consists of various tools for geolocating and routing.

9) 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.

10) 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.

[Notes by : Deshmukh D.R.]


18

11) plotly
The plotly package provides online interactive and quality graphs. This package
extends upon the JavaScript library -[Link].

12) tidytext
The tidytext package provides various functions of text mining for word processing
and carrying out analysis through ggplot, dplyr, and other miscellaneous tools.

13) stringr
The stringr package provides simplicity and consistency to use wrappers for the
'stringi' package. The stringi package facilitates common string operations.

14) reshape2
This package facilitates flexible reorganization and aggregation of data using melt ()
and decast () functions.

15) dichromat
The R dichromat package is used to remove Red-Green or Blue-Green contrasts from
the colors.

16) digest
The digest package is used for the creation of cryptographic hash objects of R
functions.

17) 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."

18) 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.

[Notes by : Deshmukh D.R.]


19

19) e1071
The e1071 library provides useful functions which are essential for data analysis like
Naive Bayes, Fourier Transforms, SVMs, Clustering, and other miscellaneous functions.

20) 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.

Syntax of R Programming
R Programming is a very popular programming language which is broadly used in data
analysis. The way in which we define its code is quite simple. The "Hello World!" is the
basic program for all the languages, and now we will understand the syntax of R
programming with "Hello world" program. We can write our code either in command
prompt, or we can use an R script file.

1. R Command Prompt
It is required that we have already installed the R environment set up in our system to
work on the R command prompt. After the installation of R environment setup, we can
easily start R command prompt by typing R in our Windows command prompt. When
we press enter after typing R, it will launch interpreter, and we will get a prompt on
which we can code our program.

[Notes by : Deshmukh D.R.]


20

"Hello, World!" Program

The code of "Hello World!" in R programming can be written as:kip 10s

In the above code, the first statement defines a string variable string, where we assign
a string "Hello World!". The next statement print() is used to print the value which is
stored in the variable string.

2. R Script File
The R script file is another way on which we can write our programs, and then we
execute those scripts at our command prompt with the help of R interpreter known
as Rscript. We make a text file and write the following code. We will save this file with
.R extension as:

Demo.R

1. string <-"Hello World!"


2. print(string)

To execute this file in Windows and other operating systems, the process will remain
the same as mentioned below.

When we press enter it will give us the following output:

Comments
In R programming, comments are the programmer readable explanation in the source
code of an R program. The purpose of adding these comments is to make the source
code easier to understand. These comments are generally ignored by compilers and
interpreters.

[Notes by : Deshmukh D.R.]


21

In R programming there is only single-line comment. R doesn't support multi-line


comment. But if we want to perform multi-line comments, then we can add our code
in a false block.

Single-line comment

1. #My First program in R programming


2. string <-"Hello World!"
3. print(string)

The trick for multi-line comment

1. #Trick for multi-line comment


2. if(FALSE) {
3. "R is an interpreted computer programming language which was created by

4. Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand "
5. }
6. #My First program in R programming
7. string <-"Hello World!"
8. print(string)

Data Types in R Programming


In programming languages, we need to use various variables to store various
information. Variables are the reserved memory location to store values. As we create
a variable in our program, some space is reserved in memory.

In R, there are several data types such as integer, string, etc. The operating system
allocates memory based on the data type of the variable and decides what can be
stored in the reserved memory.

[Notes by : Deshmukh D.R.]


22

There are the following data types which are used in R programming:

Data Example Description


type

Logical True, False It is a special data type for data with only two
possible values which can be construed as
true/false.

Numeric 12,32,112,5432 Decimal value is called numeric in R, and it is the


default computational data type.

Integer 3L, 66L, 2346L Here, L tells R to store the value as an integer,

Complex Z=1+2i, t=7+3i A complex value in R is defined as the pure


imaginary value i.

Character 'a', '"good'", In R programming, a character is used to represent


"TRUE", '35.4' string values. We convert objects into character
values with the help [Link]() function.

Raw A raw data type is used to holds raw bytes.

Let's see an example for better understanding of data types:

1. #Logical Data type


2. variable_logical<- TRUE
3. cat(variable_logical,"\n")
4. cat("The data type of variable_logical is ",class(variable_logical),"\n\n")
5.
6. #Numeric Data type
7. variable_numeric<- 3532
8. cat(variable_numeric,"\n")

[Notes by : Deshmukh D.R.]


23

9. cat("The data type of variable_numeric is ",class(variable_numeric),"\n\n")


10.
11. #Integer Data type
12. variable_integer<- 133L
13. cat(variable_integer,"\n")
14. cat("The data type of variable_integer is ",class(variable_integer),"\n\n")
15.
16. #Complex Data type
17. variable_complex<- 3+2i
18. cat(variable_complex,"\n")
19. cat("The data type of variable_complex is ",class(variable_complex),"\n\n")
20.
21. #Character Data type
22. variable_char<- "Learning r programming"
23. cat(variable_char,"\n")
24. cat("The data type of variable_char is ",class(variable_char),"\n\n")
25.
26. #Raw Data type
27. variable_raw<- charToRaw("Learning r programming")
28. cat(variable_raw,"\n")
29. cat("The data type of variable_char is ",class(variable_raw),"\n\n")

When we execute the following program, it will give us the following output:

[Notes by : Deshmukh D.R.]


24

Data Structures in R Programming


Data structures are very important to understand. Data structure are the objects which we will
manipulate in our day-to-day basis in R. Dealing with object conversions is the most common
sources of despairs for beginners. We can say that everything in R is an object.

R has many data structures, which include:

1. Atomic vector
2. List
3. Array
4. Matrices
5. Data Frame
6. Factors

Vectors
A vector is the basic data structure in R, or we can say vectors are the most basic R data
objects. There are six types of atomic vectors such as logical, integer, character, double, and
raw. "A vector is a collection of elements which is most commonly of mode
character, integer, logical or numeric" A vector can be one of the following two types:

1. Atomic vector
2. Lists

List
In R, the list is the container. Unlike an atomic vector, the list is not restricted to be a single
mode. A list contains a mixture of data types. The list is also known as generic vectors
because the element of the list can be of any type of R object. "A list is a special type of
vector in which each element can be a different type."

[Notes by : Deshmukh D.R.]


25

Backward Skip 10sPlay VideoForward Skip 10s

We can create a list with the help of list() or [Link](). We can use vector() to create a required
length empty list.

Arrays
There is another type of data objects which can store data in more than two dimensions
known as arrays. "An array is a collection of a similar data type with contiguous
memory allocation." Suppose, if we create an array of dimension (2, 3, 4) then it creates
four rectangular matrices of two rows and three columns.

In R, an array is created with the help of array() function. This function takes a vector as an
input and uses the value in the dim parameter to create an array.

Matrices
A matrix is an R object in which the elements are arranged in a two-dimensional rectangular
layout. In the matrix, elements of the same atomic types are contained. For mathematical
calculation, this can use a matrix containing the numeric element. A matrix is created with
the help of the matrix() function in R.

Syntax

The basic syntax of creating a matrix is as follows:

1. matrix(data, no_row, no_col, by_row, dim_name)

Data Frames
A data frame is a two-dimensional array-like structure, or we can say it is a table in which
each column contains the value of one variable, and row contains the set of value from each
column.

There are the following characteristics of a data frame:

1. The column name will be non-empty.


2. The row names will be unique.
3. A data frame stored numeric, factor or character type data.
4. Each column will contain same number of data items.

Factors

[Notes by : Deshmukh D.R.]


26

Factors are also data objects that are used to categorize the data and store it as levels. Factors
can store both strings and integers. Columns have a limited number of unique values so that
factors are very useful in columns. It is very useful in data analysis for statistical modeling.

Factors are created with the help of factor() function by taking a vector as an input
parameter.

Variables in R Programming
Variables are used to store the information to be manipulated and referenced in the R
program. The R variable can store an atomic vector, a group of atomic vectors, or a
combination of many R objects.

Language like C++ is statically typed, but R is a dynamically typed, means it check the
type of data type when the statement is run. A valid variable name contains letter,
numbers, dot and underlines characters. A variable name should start with a letter or
the dot not followed by a number.

Name of Validity Reason for valid and invalid


variable

_var_name Invalid Variable name can't start with an underscore(_).

var_name, Valid Variable can start with a dot, but dot should not be
[Link] followed by a number. In this case, the variable will
be invalid.

var_name% Invalid In R, we can't use any special character in the variable


name except dot and underscore.

2var_name Invalid Variable name cant starts with a numeric digit.

.2var_name Invalid A variable name cannot start with a dot which is


followed by a digit.

var_name2 Valid The variable contains letter, number and underscore


and starts with a letter.

[Notes by : Deshmukh D.R.]


27

Assignment of variable
In R programming, there are three operators which we can use to assign the values to
the variable. We can use leftward, rightward, and equal_to operator for this purpose.

There are two functions which are used to print the value of the variable i.e., print() and
cat(). The cat() function combines multiples values into a continuous print output.

1. # Assignment using equal operator.


2. variable.1 = 124
3.
4. # Assignment using leftward operator.
5. variable.2 <- "Learn R Programming"
6.
7. # Assignment using rightward operator.
8. 133L -> variable.3
9.
10. print(variable.1)
11. cat ("variable.1 is ", variable.1 ,"\n")
12. cat ("variable.2 is ", variable.2 ,"\n")
13. cat ("variable.3 is ", variable.3 ,"\n")

When we execute the above code in our R command prompt, it will give us the
following output:

Data types of variable


R programming is a dynamically typed language, which means that we can change the
data type of the same variable again and again in our program. Because of its dynamic
nature, a variable is not declared of any data type. It gets the data type from the R-
object, which is to be assigned to the variable.

We can check the data type of the variable with the help of the class() function. Let's
see an example:

[Notes by : Deshmukh D.R.]


28

1. variable_y<- 124
2. cat("The data type of variable_y is ",class(variable_y),"\n")
3.
4. variable_y<- "Learn R Programming"
5. cat(" Now the data type of variable_y is ",class(variable_y),"\n")
6.
7. variable_y<- 133L
8. cat(" Next the data type of variable_y becomes ",class(variable_y),"\n")

When we execute the above code in our R command prompt, it will give us the
following output:

Keywords in R Programming
In programming, a keyword is a word which is reserved by a program because it has a
special meaning. A keyword can be a command or a parameter. Like in C, C++, Java,
there is also a set of keywords in R. A keyword can't be used as a variable name.
Keywords are also called as "reserved names."

There are the following keywords as per ?reserved or help(reserved) command:

if else repeat

while function for

next break TRUE

FALSE NULL Inf

NaN NA NA_integer_

NA_real_ NA_complex_ NA_character_

[Notes by : Deshmukh D.R.]


29

1) if
The if statement consists of a Boolean expression which is followed by one or more
statements. In R, if statement is the simplest conditional statement which is used to
decide whether a block of the statement will be executed or not.

Example:

1. a<-11
2. if(a<15)
3. + print("I am lesser than 15")

Output:

2) else
The R else statement is associated with if statement. When the if statement's condition
is false only then else block will be executed. Let see an example to make it clear:

Example:

[Notes by : Deshmukh D.R.]


30

1. a<-22
2. if(a<20){
3. cat("I am lesser than 20")
4. }else{
5. cat("I am larger than 20")
6. }

Output:

3) repeat
The repeat keyword is used to iterate over a block of code multiple numbers of times.
In R, repeat is a loop, and in this loop statement, there is no condition to exit from the
loop. For exiting the loop, we will use the break statement.

Example:

1. x <- 1
2. repeat {
3. cat(x)
4. x = x+1
5. if (x == 6){
6. break
7. }
8. }

Output:

4) while
A while keyword is used as a loop. The while loop is executed until the given condition
is true. This is also used to make an infinite loop.

[Notes by : Deshmukh D.R.]


31

Example:

1. a <- 20
2. while(a!=0){
3. cat(a)
4. a = a-2
5. }

Output:

5) function
A function is an object in R programming. The keyword function is used to create a
user-define function in R. R has some pre-defined functions also, such as seq, mean,
and sum.

Example:

1. [Link]<- function(n) {
2. for(i in 1:n) {
3. a <- i^2
4. print(a)
5. }
6. }
7. [Link](6)

Output:

[Notes by : Deshmukh D.R.]


32

6) for
The for is a keyword which is used for looping or iterating over a sequence (dictionary,
string, list, set or tuple).

We can execute a set of a statement once for each item in the iterator (list, set, tuple,
etc.) with the help of for loop.

Example:

1. v <- LETTERS[1:4]
2. for ( i in v) {
3. print(i)
4. }

Output:

7) next
The next keyword skips the current iteration of a loop without terminating it. When R
parser found next, it skips further evaluation and starts the new iteration of the loop.

Example:

1. v <- LETTERS[1:6]
2. for ( i in v) {
3. if (i == "D") {
4. next
5. }
6. print(i)
7. }

Output:

[Notes by : Deshmukh D.R.]


33

8) break
The break keyword is used to terminate the loop if the condition is true. The control
of the program firstly passes to the outer statement then passes to the body of the
break statement.

Example:

1. n<-1
2. while(n<10){
3. if(n==3)
4. break
5. n=n+1
6. cat(n,"\n")
7. }
8. cat("End of the program")

Output:

9) TRUE/FALSE
The TRUE and FALSE keywords are used to represent a Boolean true and Boolean false.
If the given statement is true, then the interpreter returns true else the interpreter
returns false.

[Notes by : Deshmukh D.R.]


34

10) NULL
In R, NULL represents the null object. NULL is used to represent missing and undefined
values. NULL is the logical representation of a statement which is neither TRUE nor
FALSE.

Example:

1. [Link](list(a = 1, b = "c"))

Output:

11) Inf and NaN


The [Link] and [Link] function returns a vector of the same length indicating which
elements are finite or infinite.

Inf and -Inf are positive and negative infinity. NaN stands for 'Not a Number.' NaN
applies on numeric values and real and imaginary parts of complex values, but it will
not apply to the values of integer vectors.

Usage

1. [Link](x)
2. [Link](x)
3. [Link](x)
4.
5. Inf
6. NaN

12) NA

[Notes by : Deshmukh D.R.]


35

NA is a logical constant of length 1 that contains a missing value indicator. It can be


coerced to any other vector type except raw. There are other types of constant also,
such as NA_Integer_, NA_real_, NA_complex_, and NA_character. These constants are
of the other atomic vector type which supports missing values.

Usage

1. NA
2. [Link](x)
3. anyNA(x, recursive = FALSE)
4.
5. ## S3 method for class '[Link]'
6. [Link](x)
7.
8. [Link](x) <- value

Operators in R
In computer programming, an operator is a symbol which represents an action. An
operator is a symbol which tells the compiler to perform
specific logical or mathematical manipulations. R programming is very rich in built-
in operators.

In R programming, there are different types of operator, and each operator performs
a different task. For data manipulation, There are some advance operators also such
as model formula and list indexing.

There are the following types of operators used in R:

[Notes by : Deshmukh D.R.]


36

Arithmetic Operators
Arithmetic operators are the symbols which are used to represent arithmetic math
operations. The operators act on each and every element of the vector. There are
various arithmetic operators which are supported by R.

S. Operator Descrip on Example


No

1. + This operator is used to b <- c(11, 5, 3)


print(a+b)
add two vectors in R. a <-
c(2, 3.3, 4) It will give us the following output:
[1] 13.0 8.3 5.0

2. - This operator is used to b <- c(11, 5, 3)


print(a-b)
divide a vector from
another one. a <- c(2, 3.3, It will give us the following output:
4)
[1] -9.0 -1.7 3.0

3. * This operator is used to b <- c(11, 5, 3)


print(a*b)
multiply two vectors with
each other. a <- c(2, 3.3, It will give us the following output:
4)
[1] 22.0 16.5 4.0

4. / This operator divides the b <- c(11, 5, 3)


print(a/b)
vector from another one.
It will give us the following output:
a <- c(2, 3.3, 4)
[1] 0.1818182 0.6600000
4.0000000

5. %% This operator is used to b <- c(11, 5, 3)


print(a%%b)
find the remainder of the
first vector with the It will give us the following output:
second vector. a <- c(2,
[1] 2.0 3.3 0
3.3, 4)

6. %/% This operator is used to a <- c(2, 3.3, 4)


b <- c(11, 5, 3)
find the division of the print(a%/%b)

[Notes by : Deshmukh D.R.]


37

first vector with the It will give us the following output:


second(quotient). [1] 0 0 4

7. ^ This operator raised the b <- c(11, 5, 3)


print(a^b)
first vector to the
exponent of the second It will give us the following output:
vector. a <- c(2, 3.3, 4)
[1] 0248.0000 391.3539
4.0000

Relational Operators
A relational operator is a symbol which defines some kind of relation between two
entities. These include numerical equalities and inequalities. A relational operator
compares each element of the first vector with the corresponding element of the
second vector. The result of the comparison will be a Boolean value. There are the
following relational operators which are supported by R:

S. Operator Descrip on Example


No

1. > This operator will return a <- c(1, 3, 5)


b <- c(2, 4, 6)
TRUE when every print(a>b)
element in the first
vector is greater than It will give us the following output:
the corresponding [1] FALSE FALSE FALSE
element of the second
vector.

2. < This operator will return a <- c(1, 9, 5)


b <- c(2, 4, 6)
TRUE when every print(a<b)
element in the first
vector is less then the It will give us the following output:
corresponding element [1] FALSE TRUE FALSE
of the second vector.

[Notes by : Deshmukh D.R.]


38

3. <= This operator will return a <- c(1, 3, 5)


b <- c(2, 3, 6)
TRUE when every print(a<=b)
element in the first
vector is less than or It will give us the following output:
equal to the [1] TRUE TRUE TRUE
corresponding element
of another vector.

4. >= This operator will return a <- c(1, 3, 5)


b <- c(2, 3, 6)
TRUE when every print(a>=b)
element in the first
vector is greater than or It will give us the following output:
equal to the [1] FALSE TRUE FALSE
corresponding element
of another vector.

5. == This operator will return a <- c(1, 3, 5)


b <- c(2, 3, 6)
TRUE when every print(a==b)
element in the first
vector is equal to the It will give us the following output:
corresponding element [1] FALSE TRUE FALSE
of the second vector.

6. != This operator will return a <- c(1, 3, 5)


b <- c(2, 3, 6)
TRUE when every print(a>=b)
element in the first
vector is not equal to It will give us the following output:
the corresponding [1] TRUE FALSE TRUE
element of the second
vector.

Logical Operators
The logical operators allow a program to make a decision on the basis of multiple
conditions. In the program, each operand is considered as a condition which can be
evaluated to a false or true value. The value of the conditions is used to determine the

[Notes by : Deshmukh D.R.]


39

overall value of the op1 operator op2. Logical operators are applicable to those
vectors whose type is logical, numeric, or complex.

The logical operator compares each element of the first vector with the corresponding
element of the second vector.

There are the following types of operators which are supported by R:

S. Operator Descrip on Example


No

1. & This operator is known a <- c(3, 0, TRUE, 2+2i)


b <- c(2, 4, TRUE, 2+3i)
as the Logical AND print(a&b)
operator. This operator
takes the first element It will give us the following output:
of both the vector and [1] TRUE FALSE TRUE TRUE
returns TRUE if both the
elements are TRUE.

2. | This operator is called a <- c(3, 0, TRUE, 2+2i)


b <- c(2, 4, TRUE, 2+3i)
the Logical OR print(a|b)
operator. This operator
takes the first element It will give us the following output:
of both the vector and [1] TRUE TRUE TRUE TRUE
returns TRUE if one of
them is TRUE.

3. ! This operator is known a <- c(3, 0, TRUE, 2+2i)


print(!a)
as Logical NOT
operator. This operator It will give us the following output:
takes the first element
[1] FALSE TRUE FALSE
of the vector and gives FALSE
the opposite logical
value as a result.

4. && This operator takes the a <- c(3, 0, TRUE, 2+2i)


b <- c(2, 4, TRUE, 2+3i)
first element of both print(a&&b)
the vector and gives
TRUE as a result, only if It will give us the following output:
both are TRUE. [1] TRUE

[Notes by : Deshmukh D.R.]


40

5. || This operator takes the a <- c(3, 0, TRUE, 2+2i)


b <- c(2, 4, TRUE, 2+3i)
first element of both print(a||b)
the vector and gives the
result TRUE, if one of It will give us the following output:
them is true. [1] TRUE

Assignment Operators
An assignment operator is used to assign a new value to a variable. In R, these
operators are used to assign values to vectors. There are the following types of
assignment

S. Operator Descrip on Example


No

1. <- or = or These operators a <- c(3, 0, TRUE, 2+2i)


b <<- c(2, 4, TRUE, 2+3i)
<<- are known as left d = c(1, 2, TRUE, 2+3i)
assignment print(a)
print(b)
operators.
print(d)

It will give us the following output:


[1] 3+0i 0+0i 1+0i 2+2i
[1] 2+0i 4+0i 1+0i 2+3i
[1] 1+0i 2+0i 1+0i 2+3i

2. -> or ->> These operators c(3, 0, TRUE, 2+2i) -> a


c(2, 4, TRUE, 2+3i) ->> b
are known as print(a)
right assignment print(b)
operators.
It will give us the following output:
[1] 3+0i 0+0i 1+0i 2+2i
[1] 2+0i 4+0i 1+0i 2+3i

[Notes by : Deshmukh D.R.]

You might also like