R is a powerful programming language and environment for statistical computing, data exploration, analysis, and visualization. It is free, open source, and has a strong, rapidly growing community where users and developers share their experience and actively contribute to the development of more than 7,500 packages, so that R can deal with problems in a wide range of fields .
R as a programming language: R, as a programming language, has been evolving and developing over the last 20 years. Its goal is quite clear to make it easy and flexible to perform comprehensive statistical computing, data explo-ration, and visualization.
R as a computing environment: R, as a computing environment, is lightweight and ready to use.Compared to some other famous statistical software, for ex-ample, MATLAB and SAS, R is much smaller and easier to deploy.
Introduction to R
1.1 Overview of R programming
Evolution of R: R is a programming language and software environment for statistical analysis, graphics representation and reporting. R was initially writ-ten by Ross Ihaka and Robert Gentleman at the Department of Statistics of the University of Auckland in Auckland, New Zealand. R made its first appearance in 1993.A large group of individuals has contributed to R by sending code and bug reports. Since mid-1997 there has been a core group (the ”R Core Team”) who can modify the R source code archive.
1
2
CHAPTER 1.
INTRODUCTION TO R
1.2 Need for R:
The following points describe why R language should be used:
Free of charge: R is totally free. It is available under the terms of the Free Software Foundation’s GNU General Public License in source code form.
Open-source: R and most of its packages are fully open source. Thou-sands of developers are constantly reviewing the source code of the pack-ages to check whether there are bugs to fix or things to improve.
Popular: R is a very popular as a statistical programming language and platform to perform data mining,analysis, and visualization.
Flexible: R is a dynamic script language. It is highly flexible to allow programming styles in multiple paradigms, including functionality pro-gramming and object-oriented programming.
Reproducible: When using software based on a graphical user interface, you only need to choose from menus and click buttons.
Rich resources: R has a huge, rapidly increasing number of online re-sources. One type of resource is extension packages. There are, at the time of writing this, more than 7,500 packages available at CRAN (short for Comprehensive R Archive Network), a world-wide network of mirror servers from which you can get identical, up-to-date, R distributions and packages.
Strong community: The community of R consists of not only R devel-opers but also, (the majority), R users from a wide range of backgrounds
such as statistics, econometrics, finance, bioinformatics, mechanical en-gineering, physics, medicine, and so on.A great number of R developers actively contribute to open source projects or packages written in R.
Cutting-edge: Many R users are professional researchers in statistics, econometrics,or other disciplines.Quite often,authors publish their new pa-pers along with a new package that includes the cutting-edge techniques presented in the paper.
R Programming Language and Python are both used extensively for Data Sci-ence. Both are very useful and open-source languages as well. For data analy-sis, statistical computing, and machine learning Both languages are strong tools with sizable communities and huge libraries for data science jobs. A theoretical comparison between R and Python is provided below:
S.No | R Programming | Python |
1. | R is a statistical language used for the analysis and visual repre-sentation of data. | Python is a general-purpose lan- guage that is used Well-suited for many programming domains, including data science, web de-velopment, software develop-ment, and gaming. |
2. | Very popular in academia and research, finance and data sci-ence. | Well-suited for many program- ming domains, including data science, web development, soft-ware development, and gaming. |
3. | R has fewer libraries compared to Python and is easy to know. | Python has a lot of libraries. However, it can be complex to understand all of them. |
4. | R’s statistical packages are highly powerful. | Python’s statistical packages are less powerful. |
5. | R is generally used when the data analysis task requires stan-dalone computation(analysis) and processing. | Python is mainly used when the data analysis needs to be inte-grated with web applications. |
6. | A few IDEs for the R language are RStudio, StatET, etc. | There are many Python IDEs available to choose from, a few of them are Jupyter Notebook, Spyder, Pycharm, etc. |
4
CHAPTER 1. INTRODUCTION TO R
Flavors of R
R vs. RStudio: R is an open-source programming language that is used for programming, data analysis and data visualisation. It is widely used for sta-tistical analysis. RStudio is actually an add-on to R: it takes the R software and adds to it a very user-friendly graphical interface. RStudio, on the other hand, is an IDE(Integrated Development Environment) designed to enhance the R programming experience. It provides a user-friendly interface with vari-ous tools and features that streamline the development process. The RStudio interface includes panes for code editing, console output, data visualization, and package management, making it easier to organize and execute R scripts.
1.3. INSTALLING R
1.3 Installing R
5
To install R, you need to visit R’s official website(https://www.r-project.org/), download R (https://cran.r-project.org/mirrors.html),choose a nearby mirror, and download a version for your operating system.
If you are using Windows, just download an installer for the latest version. To install R, run the Windows installer that you just downloaded.In the Win-dows drop-down, when choosing the components to install, the installer lists four components. Here, Core files means the core libraries of R, and the Mes-sage translations component provides many versions of translations of warning and error messages in a list of supported languages. If you are using a modern computer purchased in recent years, it is most likely to support 64-bit programs and should be running a 64-bit operating system, so the default option will be 64-bit files.
Another option you may feel confused about is whether to save the R
version number in the registry. Checking these options makes it easier for other programs to detect which R version is installed. If you are sure you only use R in its own, just go ahead with the defaults.
6
CHAPTER 1.
INTRODUCTION TO R
Then, the installation starts copying files to your hard drive.
Installing R Studio
You can download the latest release of RStudio at
1.4. ENVIRONMENT SETUP WITH R STUDIO
7
https://www.rstudio.com/products/rstudio/download.
1.4 Environment setup with R Studio
RStudio is a powerful user interface for R programming. It’s free, open source, and works on multiple platforms including Windows,Mac, and Linux.
RStudio has very powerful features that hugely boost your productivity in data analysis and visualization. It supports syntax highlighting, autocomple-tion, multi-tabbed views, file management, graphics viewport, package man-agement, integrated help viewer, code formatting, version control, interactive debugging, and many more features.
The main window of R Studio consists of several parts. Each part is called a pane and performs different functions. These panes are well designed for data analysts to work with data.
1. The console: The console works exactly like a Command Prompt or terminal. In fact, when you type in a command at the console, RStudio
8
CHAPTER 1. INTRODUCTION TO R
will submit the request to the R engine. It is the R engine that executes all the commands. The role of RStudio is to stand in the middle, take inputs from user to the R engine, and present the results it returns.
Press Ctrl + Enter to execute the selected lines.
Press Ctrl + Shift + S to source the current document, that is, to evaluate all the expressions sequentially in the current document.
Press Tab or Ctrl + Space to show an autocompletion list of vari-ables and functions that match your current typing.
Each time you create a new object (a variable or function), a new entry will appear in the Environment pane. The entry shows the variable name and a short description of its value. When you change the value of a symbol or even remove that symbol, you actually modify the environment so that the environment pane reflects your change.
Type the function name in the Search box and find it directly.
Type the function name in the console and press F1.
Type ? before the function name and execute it.
Packages in R Programming language are a set of R functions, compiled code, and sample data. A package is a container of predefined functions, which are often designed to be general enough to solve a certain range of prob-lems.These are stored under a directory called “library” within the R envi-ronment. By default, R installs a group of packages during installation. Once we start the R console, only the default packages are available by default. Other packages that are already installed need to be loaded explicitly to be utilized by the R program that’s getting to use them. R is powerful not only because of its rich source of packages, but also because of the well-maintained package archive system called The Comprehensive R Archive Network, or CRAN.
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:
10
CHAPTER 1. INTRODUCTION TO R
1.5.1 Installing packages
How to Install Extra Packages for Windows Users in R:
In Windows you can use the Packages menu. You have several options, but Install Package(s) is the one you will want most often. After you have selected a local mirror site you are presented with a list of available binary packages from which you can choose the ones you require (See the figure).
Once you have selected the packages you require, click OK at the bottom and the packages will be downloaded and installed directly into R.
How to Install Extra Packages for Windows Users in R Studio: RStu-dio also provides an easy way to install packages. Just go to the Packages pane and click on Install. The following dialog appears:
1.5. PACKAGES
11
As the package description shows, a package may depend on other packages. In other words, when you call a function in the package, the function also calls some functions in other packages, which requires that you also install those packages as well. Fortunately, install.packages() is smart enough to know the dependency structure of the package to install and will install those packages first.
You can see what packages are installed using the following command:
installed.packages()
1.5.2 Updating packages
By default, the install.packages() function installs the latest version of the specified packages. Once they are installed, the package version stays fixed. However, the packages may be updated to fix bugs or add new features. Some-times, an updated version of a package may deprecate functions in older versions with warnings. In these cases, we may update it.
RStudio provides an Update button next to Install in the package pane. We can also use the following function and choose which packages are going to be updated.
update.packages()
Both RStudio and the preceding function scan newer versions of packages and install these packages along with dependencies if necessary.
12
CHAPTER 1.
INTRODUCTION TO R
1.6 Running and manipulating packages
Once you have some packages installed you need to be able to access the new commands available in these packages. The packages are not automatically ready for use and you must load them to make the library of code routines available for use.
We can see which packages are loaded and running using the following command:
search()
If you do this before you load any additional packages, you will see the core form of the R basic distribution. The following resulted from the search() command on a Mac OS X with R version.2.7.1 installed.
You can see that the basic R program is actually comprised of several smaller units, no less than seven packages in this case. By default the new packages are not automatically ready for use but need to be loaded.
1.7. BASIC OBJECTS
1.6.1 Loading Packages
13
It is simple to load packages as required. Start by issuing the following command:
library(package)
The library() command retrieves the appropriate package and makes its con-tents available for you.Second way is that, we can call package::function() to only use the function without attaching the whole package to the environment.
Example:To calculate the skewness of numeric vector x, we can attach the package first and directly call the function:
library(moments)skewness(x)
Alternatively, we can call package functions without attaching the package, using ::
moments :: skewness(x)
1.6.2 Removing or Unloading Packages
If you have loaded some packages and want to remove one, perhaps to free up an overwritten command, you can use the detach() command like so:
detach(package : name)
You simply replace the name part with the name of the package that you want to remove. Once removed, a package is not totally gone; you can still use the library() command to get it back when required.
Data objects are the fundamental items that you work with in R.Every task involves various different types of objects. Each object has a different goal and behavior. There are many ways to manipulate your data, and understanding how to do this is important in learning about R because the more you know about the way R handles objects, the better use you can make of R as an ana-lytical tool.
R objects
14
CHAPTER 1.
INTRODUCTION TO R
Data Objects (or) Data Structures in R
A vector is the basic data structure in R, or we can say vectors are the most basic R data objects. A vector is a group of primitive values of the same type. It can be a group of numbers, true/false values, texts, and values of some other type. It is one of the building blocks of all R objects.
There are several types of vectors in R. They are distinct from each other in the type of elements they store.
Types of vectors in R
15
Numeric vector: A numeric vector is a vector of numeric values. A scalar number is the simplest numeric vector.
Example: x <−1.5 (or) x = 1.5
Vectors of numeric type can be created by using any one of the following commands.
Vectors are generally created using the c() function.
numeric() is used to create a zero vector of a given length.
A sequence of vectors can be created by using colon operator (:).
A more general way to produce a numeric sequence is seq().
Examples:
Output: [1] 1 5 4 9 0
Output: [1] 0 0 0 0 0 0 0 0 0 0
Output: [1] 1 2 3 4 5 6 7
Output: [1] 2 1 0 -1 -2
Output: [1] 1 3 5 7 9
Logical vector: A logical vector stores a group of TRUE or FALSE values. They are basically yes or no to denote the answers to a group of logical ques-tions.The simplest logical vectors are TRUE and FALSE themselves.
Examples:
Output: [1] TRUE
Output:[1] FALSE
Output: [1] FALSE FALSE
16
CHAPTER 1. INTRODUCTION TO R
Output: [1] TRUE TRUE TRUE FALSE
7.w <−c(1, 4)%in%c(1, 2, 3) Output: [1] TRUE FALSE
Character Vector:A character vector is a group of strings. Strings in R can contain alphabets, numbers, and symbols. In R, there are two different ways to create a character vector either by typing string between double quotes(””) or single quotes(”).
Examples
Output: [1] ”Sun” ”Mon” ”Tue” ”Wed” ”Thurs” ”Fri” ”Sat”
Complex Vector: Complex vectors are vectors used to store numbers with an imaginary component. Complex vectors are vectors of complex values.
Examples:
Output: [1] 4+3i
Output: [1] 2-2i
Raw Vector: Raw vectors basically store raw binary data that is represented in the hexadecimal form. To save and work with data at the byte level in R, use the raw data type.Raw vectors can be created using the raw() function.
Examples
Output:
[1] 00 00 00 00 00 00 00 00 00 00 00 00
raw variable <−charT oRaw(”Welcome to Programiz”) print(raw variable)
1.8. VECTOR
17
Output:
[1] 57 65 6c 63 6f 6d 65 20 74 6f 20 50 72 6f 67 72 61 6d 69 7a
1.8.2 Subsetting vectors
Subsetting a vector means accessing some specific entries or a subset of the vector. We can access the elements of a vector with the help of vector indexing. Indexing denotes the position where the value in a vector is stored. We perform indexing by specifying an integer value in square braces [ ] next to our vector.
Examples:
1. x <−2 : 10
Output:[1] 2 3 4 5 6 7 8 9 10 x[4]
Output: [1] 5
x[c(2, 4, 8)]
Output: | [1] 3 5 9 |
x[4 : 7] | |
Output: x[−4] | [1] 5 6 7 8 |
Output: | [1] 2 3 4 6 7 8 9 10 |
x[c(TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE)]
Output: [1] 2 6 8 9 10
Output: [1] FALSE TRUE TRUE w[2]
Output: [1] FALSE
Output: [1] ”Thurs” ”Fri” ”Sat”
1.8.3 Overwriting (or) Replacing Elements
We can overwrite a specific subset of a vector (or) overwrite multiple ele-ments at different positions. Like subsetting, logical selectors are also accepted for overwriting.
1. b <−c(3, 2, 4, 4, 1, 2, 4, 1, 0, 0, 5)
Output: [1] 3 2 4 4 1 2 4 1 0 0 5
18
CHAPTER 1. INTRODUCTION TO R
The code overwrites the third element of b, which was originally 4, with a new value, 6.
b[3] <−6
Output: [1] 3 2 6 4 1 2 4 1 0 0 5
-2, -0.5,and -1, respectively; all else remains the same.
b[c(2, 4, 6)] <−c(−2, −0.5, −1)
Output: [1] 3.0 -2.0 6.0 -0.5 1.0 -1.0 4.0 1.0 0.0 0.0 5.0
b[7 : 10] <−100
Output: [1] 3.0 -2.0 6.0 -0.5 1.0 -1.0 100.0 100.0 100.0 100.0 5.0
1.8.4 Named Vectors
A named vector is not a specific type of vector parallel to a numeric or logical vector. It is a vector with names corresponding to the elements. We can give names to a vector when we create it.
Example: x <−c(a = 1, b = 2, c = 3)
Output: a b c
1 2 3
We can access the elements with a single-valued character vector.
Examples: x[”a”]
Output: a
1
x[c(”a”, ”c”)]
Output: a c
1 3
We can get the names of a vector with names() :
Example: names(x).
Output: [1] ”a” ”b” ”c”
The names of a vector are not fixed. We can change the names of a vector by assigning another character vector to its names.
names(x) <−c(”x”, ”y”, ”z”)
1.8. VECTOR
19
Output:
x y z 1 2 3
x[”z”]
Output:
z 3
If the names are no longer needed, we can simply remove the vector’s names using NULL, a special object that represents undefined value: names(x) <−NU LL
Output: [1] 1 2 3
1.8.5 Extracting an element
While [] creates a subset of a vector, [[ ]] extracts an element from a vector. For simple vectors, using [] and [[]] to get one element will produce the same result.But it does not work with vectors of more than one element:
Example: x[[”a”]]
Output: [1] 1
Class of vectors We can obtain information about the type of object by using the class() command. The class() function tells us the class of any R object.
Syntax: class(object)
Examples:
Output: [1] ”numeric”
Output:[1] ”logical”
Output: [1] ”character”
1.8.6 Object-Checking Functions
Identifying the class of an object is essential for functions that operate on stored objects, especially those that behave differently depending on the class of the object. To check whether the object is a specific class or data type, you can use the is-dot functions on the object and it will return a TRUE or FALSE
20
CHAPTER 1. INTRODUCTION TO R
logical value.
Examples:
Output: [1] TRUE
Output: [1] FALSE
Output:[1] TRUE
The process of altering the data type of an object to another type is re-ferred to as coercion or data type conversion. This is a common operation in many programming languages that is used to alter data and perform various computations. When coercion is required, the language normally performs it automatically, whereas conversion is performed directly by the programmer.
Syntax: as.data type(object)
Examples:
strings <−c(”1”, ”2”, ”3”) class(strings)
Output[1] ”character”
strings + 10
Error in strings + 10 : non-numeric argument to binary operator numbers <−as.numeric(strings)
numbers
Output: [1] 1 2 3
numbers + 10
Output: [1] 11 12 13
The arithmetic operations of numeric vectors are very simple. They basi-cally follow two rules:
Examples:
1.9. MATRIX
21
c(1, 2, 3, 4) + 2
Output: [1] 3 4 5 6
c(2, 3, 5, 7) + c(−2, −3, −5, 8)
Output: [1] 0 0 0 15
c(1, 2, 3) ∗ c(2, 3, 4)
Output: [1] 2 6 12
c(1, 2, 3)/c(2, 3, 4)
Output: 0.5000000 0.6666667 0.7500000
c(1, 2, 3)ˆ2
Output:[1] 1 4 9
c(1, 2, 3)ˆc(2, 3, 4)
Output: [1] 1 8 81
c(2, 3, 5, 7) + c(8, 9)
Output: [1] 10 12 13 16
c(2, 3, 5, 7) ∗ c(8, 9)
Output: 16 27 40 63
c(a = 1, b = 2, c = 3) + c(b = 2, c = 3, d = 4) Output:
a b c 3 5 7
1.9 Matrix
A matrix is a vector represented and accessible in two dimensions.Therefore, what applies to vectors is most likely to apply to a matrix. A matrix A as an m × n matrix; that is, A will have exactly m rows and n columns. This means A will have a total of mn entries, with each entry aij having a unique position given by its specific row (i = 1, 2, ..., m) and column (j = 1, 2, ..., n).
A =
a11
21
a
2m
a12 .. .. ..
a a22 .. .. ..
.. .. .. .. .. ..
.. .. .. .. .. ..
.. .. .. .. .. ..
an1 an2 .. .. .. amn
a1m
22
1.9.1 Creating a matrix
CHAPTER 1. INTRODUCTION TO R
We can call matrix() to create a matrix from a vector.By default the matrix elements are filled coulmnwise from the given vector. If we want to store the given elements rowwise, the argument byrow should be made ”TRUE.” Syntax:
matrix(data, nrow, ncol, byrow, dim name), where
data - The first argument in matrix function is data. It is the input vector which is the data elements of the matrix.
nrow - The second argument is the number of rows which we want to create in the matrix.
ncol - The third argument is the number of columns which we want to create in the matrix.
byrow - The byrow parameter is a logical clue. If its value is true, then the input vector elements are arranged by row.
dim−name - The dim name parameter is the name assigned to the rows and columns.
Example:
1. A <−matrix(c(1, 5, 3, 0, −1, 3, 6, 2, 4), ncol = 3)
Output
2. B <−matrix(c(1, 5, 3, 0, −1, 3, 6, 2, 4), nrow = 3, byrow = TRUE) Output
3. B <−matrix(c(1, 5, 3, 0, −1, 3, 6, 2, 4), nrow = 3, byrow = FALSE) Output
1.9. MATRIX
1.9.2 Naming rows and columns
23
By default, creating a matrix does not automatically give names to its rows and columns. Sometimes, it is useful and straightforward to do so when differ-ent rows and columns have different meanings. We can give row names and/or column names when creating the matrix.
Example:
(1)matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, byrow = TRUE, dimnames = list(c(”r1”, ”r2”, ”r3”), c(”c1”, ”c2”, ”c3”)))
Output
Alternatively, we can use row names and/or column names after the matrix is created.
(2) m1 <−matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), ncol = 3)
rownames(m1) <−c(”r1”, ”r2”, ”r3”)
colnames(m1) <−c(”c1”, ”c2”, ”c3”) Output
1.9.3 Subsetting a matrix
Extracting (or)accessing elements from matrices in R is much like extracting elements from vectors. This is called matrix subsetting. Elements of a ma-trix can be accessed by using the column and row index of the element.Element extraction still uses the square-bracket operator [ ], but now it must be per-formed with both a row and a column position, given strictly in the order of [row, column].
Examples:
# Define the column and row names.
rownames = c(”row1”, ”row2”, ”row3”, ”row4”)
colnames = c(”col1”, ”col2”, ”col3”)
# Create the matrix.
P <−matrix(c(3 : 14), nrow = 4, byrow = TRUE, dimnames = list(rownames,
24
CHAPTER 1.
INTRODUCTION TO R
colnames))
Output
# Access the element at 3rd column and 1st row.
print(P [1, 3])
Output [1] 5
# Access the element at 2nd column and 4th row.
print(P [4, 2])
Output [1] 13
# Access only the 2nd row.
print(P [2, ])
Output
col1 col2 col3 6 7 8
# Access only the 3rd column.
print(P [, 3]) Output:
row1 row2 row3 row4 5 8 11 14
# We can subset it with a range of positions.
P [1 : 2, 2 : 3]
Output
# Access 2nd and 3rd column.
P [, 2 : 3]
Output
1.9. MATRIX
25
Note that the matrix has row names and column names, and we can use character vectors to subset it.
P [c(”row1”, ”row3”), c(”col1”, ”col3”)] Output
1.9.4 Omitting and Overwriting Elements from a matrix:
To delete or omit elements from a matrix, you again use square brackets,but this time with negative indexes.
Examples:
1. P [−1, ]
Output
2. P [, −2]
Output
3. P [−1, −2]
Output
26
CHAPTER 1. INTRODUCTION TO R
4. P [−1, −c(2, 3)]# this deletes the first row and then deletes the second and third columns.
row2 row3 row4 6 9 12
To overwrite particular elements, or entire rows or columns, you identify the elements to be replaced and then assign the new values.The new elements can be a single value, a vector of the same length as the number of elements to be replaced, or a vector whose length evenly divides the number of elements to be replaced.
Examples:
1. P [2, ] < −1 : 3
Output
2. P [c(1, 3), 2] < −11
Output
3. P [c(1, 3), c(1, 3)] < −c(−7, 7)
Output
1.9. MATRIX 27
A matrix is a vector represented and accessible in two dimensions; how-ever, it is still a vector in its nature. This allows us to use a one-dimensional accessor for vectors to subset a matrix.
Examples:
Output [1] 7
Output [1] 7 12 11 2
An inequality will return another logical matrix of equal size.
Example:P > 4 Output
We can use an equal-sized logical matrix for subsetting as if it is a vector.
Example:P [P > 4]
Output [1] 7 12 11 11 13 7 14
1.9.5 Arithmetic Operations on Matrices
All arithmetic operators for vectors also work with matrices as if they were vectors. These operators perform calculations element-wise, except for matrix-only operators, such as matrix product, % ∗ %.
Examples
1. P + P
Output
2. P − 2 ∗ P
Output
28
CHAPTER 1.
INTRODUCTION TO R
3. P ∗ P
Output
4. P 2
Output
5. P/P
Output
6. Q <−matrix(1 : 9, nrow = 3, ncol = 3) Q
Output
Q% ∗ %Q
Output
1.10. ARRAY
29
1.10 Array
In R, arrays are the data objects which allow us to store data in more than two dimensions. More specifically, an array is a vector that is represented and accessible in a given number of dimensions. In R, an array is created with the help of the array() function. This array() function specify the individual ele-ments in the data argument as a vector. Then specify size in the dim argument as another vector with a length corresponding to the number of dimensions. Note that array fills the entries of each layer with the elements in data in a strict column-wise fashion, starting with the first layer.
Syntax: array(data, dim = (nrow, ncol, nmat), dimnames = names), where nrow : Number of rows
ncol : Number of columns
nmat : Number of matrices of dimensions nrow ∗ ncol dimnames : Default value = NULL.
Examples:
(1) AR <−array(data = 1 : 24, dim = c(3, 4, 2)) Output
(2) Creating two vectors of different lengths.
vec1 <−c(1, 3, 5)
vec2 <−c(10, 11, 12, 13, 14, 15)
Initializing names for rows, columns and matrices
30
CHAPTER 1. INTRODUCTION TO R
col names <−c(”Col1”, ”Col2”, ”Col3”)
row names <−c(”Row1”, ”Row2”, ”Row3”) matrix names <−c(”M atrix1”, ”Matrix2”)
Taking the vectors as input to the array
res <−array(c(vec1, vec2), dim = c(3, 3, 2), dimnames = list(row names, col names, matrix names)) print(res)
Output
(3) For an array that is already created, we can call dimnames(x) to setup the names for each dimension by supplying a list of several character vectors.
a0 <− array(c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), dim = c(1, 5, 2))
dimnames(a0) <−list(c(”r1”), c(”c1”, ”c2”, ”c3”, ”c4”, ”c5”), c(”k1”, ”k2”)) Output
1.10.1 Subsetting an array
The principle of subsetting an array is exactly the same as subsetting a matrix. Here, we can supply a vector for each dimension to extract a subset of an array.The elements are accessed with the help of the index.
Examples:
1.11. LISTS
31
[1] 14 17 20 23
[1] 20 14
Output
| [ | , 1] | [ , 2] | |
[1, | ] | | 1 | 13 |
[2, | ] | | 4 | 16 |
[3, | ] | | 7 | 19 |
[4, | ] | | 10 | 22 |
4. res[c(”Row2”), c(”Col1”, ”Col3”), ”Matrix2”] Output
Col1 Col3
3 14
The list is an incredibly useful data structure.A list is a generic vector that is allowed to include different types of objects, even other lists.It is useful for its flexibility. A single list could contain a numeric matrix, a logical array, a single character string, and a factor object. For example, the result of a linear model fit in R is basically a list object that contains rich results of a linear regression such as linear coefficients (numeric vectors), residuals (numeric vectors), QR decomposition (a list containing a matrix and other objects), and so on.
We can use list() to create a list, as the function name suggests.
Examples:
1. l <−list(1, c(TRUE, FALSE), c(”a”, ”b”, ”c”))
l
Output:
32
CHAPTER 1. INTRODUCTION TO R
2. We can assign names to each list entry using named arguments.
l1 <−list(x = 1, y = c(TRUE, FALSE), z = c(”a”, ”b”, ”c”))
l1
Output:
3. foo <−list(matrix(data = 1 : 4, nrow = 2, ncol = 2), c(T, F, T, T ), ”hello”) foo
Output:
4. vec <−c(3, 4, 5, 6)
char−vec <−c(”shubham”, ”nishka”, ”gunjan”, ”sumit”) logic−vec <−c(T RUE, FALSE, FALSE, TRUE)
out−list <−list(vec, char vec, logic vec) out−list
Output:
1.11. LISTS
33
Naming List Elements: R provides a very easy way for accessing elements, i.e., by giving the name to each element of a list. By assigning names to the elements, we can access the element easily.
Example:
list−data <−list(c(”Shubham”, ”Nishka”, ”Gunjan”), matrix(c(40, 80, 60, 70, 90, 80), nrow = 2), list(”BCA”, ”MCA”, ”B.tech”))
names(list−data) <−c(”Students”, ”Marks”, ”Course”) print(list−data)
Output:
To remove names of a list, we replace the names of list with NULL. Example:
names(l1) <−NU LL l1
Output:
34
CHAPTER 1. INTRODUCTION TO R
1.11.2 Extracting an elements from a list
We can access elements of an R list in two ways.
Access components by indices: We can also access the components of the R list using indices. To access the top-level components of a R list we have to use a double slicing operator “[[ ]]” which is two square brackets (or) ”[ ]” and if we want to access the lower or inner-level components of a R list we have to use another square bracket “[ ]” along with the double slicing operator “[[ ]]“.
Examples:
1. foo[1]
Output:
2. foo[3]
Output:
[[1]]
[1] ”hello”
Output: [1] TRUE
Access components by names: All the components of a list can be named and we can use those names to access the components of the R list using the dollar $ command.
Examples:
Output: [1] 1
Output:[1] ”a” ”b” ”c”
1.11. LISTS
35
3. list data$Course
Output:
4. list data[”Marks”]
Output:
Subsetting a list: In many cases, we need to extract multiple elements from a list. These multiple members also construct a list as a subset of the original list. To subset a list, we can use single-square-bracket notation, just like what we use for vectors and matrices. We can extract some elements of a list and put them into a new list.
Example
ol1 = list data[c(”Students”, ”Marks”)] ol1
Output
1.11.3 Setting values to a List
Setting the values in a list is as straightforward as working with vectors.
Example
1. l1 <−list(x = 1, y = c(TRUE, FALSE), z = c(”a”, ”b”, ”c”))
l1$x <−0 l1 Output
36
CHAPTER 1. INTRODUCTION TO R
$x
[1] 0
$y
[1] TRUE FALSE
$z
[1] ”a” ”b” ”c”
2. If we assign a value to a nonexisting member, we will add a new member to the list with the given name or position.
l1$m <− 4 l1 Output
$x
[1] 0
$y
[1] TRUE FALSE
$z
[1] ”a” ”b” ”c”
$m
[1] 4
3. Also, we can set multiple values at the same time. l1[c(”y”, ”z”)] <−list(y = ”new value for y”, z = c(1, 2)) l1
Output
$x
[1] 0
$y
[1] ”new value for y”
$z
[1] 1 2
1.11. LISTS
37
$m
[1] 4
4. If we need to remove some of the members in a list, just assign the NULL value to them.
l1$x <−NU LL l1
Output
$y
[1] ”new value for y”
$z
[1] 1 2
$m
[1] 4
5. We can remove more than one member from a list altogether.
l1[c(”z”, ”m”)] <−NU LL
l1
Output
$y
[1] ”new value for y”
1.11.4 Other functions related to List
Many functions in R are related to lists. They are listed with illustrative examples as follows:
1. We can call is.list() to find out, whether particular variable is a list (or) not.
l2 <−list(a = c(1, 2, 3), b = c(”x”, ”y”, ”z”, ”w”)) is.list(l2)
[1] TRUE
is.list(l2$a)
[1] FALSE
Here, l2 is a list, and but l2$a is a numeric vector rather than a list.
2. We can also convert a vector to a list using as.list().
l3 <−as.list(c(a = 1, b = 2, c = 3)) l3
38
CHAPTER 1. INTRODUCTION TO R
Output
$a
[1] 1
$b
[1] 2
$c
[1] 3
unlist(l4) Output a b c
1 2 3
l4 <−list(a = 1, b = 2, c = ”hello”) unlist(l4)
Output
a b
”1” ”2”
c
”hello”
Here, l4$a and l4$b are numbers and can be converted to a character; however, but l4$c is a character vector and cannot be converted to numeric values. Therefore, their closest type that is compatible with all elements is a character vector.
1.12 Factors
Factors in R Programming Language are data structures that are imple-mented to categorize the data or represent categorical data and store it on multiple levels. These are the data objects which are used to categorize the data and to store it on multiple levels. It can store both integers and strings values, and are useful in the column that has a limited number of unique values. Examples of factors:
1. Demography: Male/Female
1.12. FACTORS
39
1.12.1 Creating a Factor
The command used to create or modify a factor in R language is factor()
with a vector as input.The two steps to creating an R factor:
Creating a vector.
Converting the vector created into a factor using function factor().
Examples:
1. data <−c(”East”, ”West”, ”East”, ”North”, ”North”, ”East”, ”West”, ”West”, ”West”, ”East”, ”North”)
print(data)
factor−data <−f actor(data) print(factor−data) Output:
[1] ”East” ”West” ”East” ”North” ”North” ”East” ”West” ”West” ”West” ”East” ”North”
[1] East West East North North East West West West East North Levels: East North West
2. music−genre <−f actor(c(”Jazz”, ”Rock”, ”Classic”, ”Classic”, ”Pop”, ”Jazz”, ”Rock”, ”Jazz”))
music−genre
Output:
[1] Jazz Rock Classic Classic Pop Jazz Rock Jazz Levels: Classic Jazz Pop Rock
3. School, ‘XYZ’ places students in groups, also called houses. Each group is assigned a unique color such as ‘red’, ‘green’, ‘blue’ or ‘yellow’. HouseColor is a vector that stores the house colors of a group of students. HouseColor <−c(‘red′, ‘green′, ‘blue′, ‘yellow′, red′, ‘green′, ‘blue′, ‘blue′) types <−f actor(HouseColor) HouseColor
print(types)
Output:
[1] “red” “green” “blue” “yellow” “red” “green” “blue” “blue”
[1] red green blue yellow red green blue blue
40
CHAPTER 1. INTRODUCTION TO R
Levels: blue green red yellow
Levels in a factor: The most important extra piece of information that a factor object contains is its levels, which store the possible values in the factor. These levels are printed at the bottom of each factor. We can extract the levels as a vector of character strings using the levels()function.
Examples:
Output: [1] ”Classic” ”Jazz” ”Pop” ”Rock”
Output: [1] “blue” “green” “red” “yellow”
as.integer(types)
Output: [1] 3 2 1 4 3 2 1 1
Changing the Order of Levels: The order of the levels in a factor can be changed by applying the factor function again with new order of the levels.
Example: new−order−data <−f actor(factor−data, levels = c(”East”, ”West”, ”North”))
print(new−order−data)
Output: [1] East West East North North East West West West East North Levels: East West North
New values can be added to the existing factor by updating the levels.
Example:
levels(music genre) <−c(levels(music genre), ”Techno”) music genre[5] <−”T echno”
print(music genre)
Output:
[1] Jazz Rock Pop Jazz Techno Classic Rock Jazz Levels: Classic Jazz Pop Rock Techno
1.12.2 Access Factor Elements
Like vectors, we can access the components of factors. The process of accessing components of factor is much more similar to the vectors. We can
1.13. DATA FRAMES
41
access the element with the help of the indexing method using [] brackets.
Examples
Output: [1] Classic
Output: [1] ”red”
Output: [1] ”green” ”yellow” ”green”
Changing Item Values in a Factor: After a factor is formed, its components can be modified but the new values which need to be assigned must be at the predefined level. Examples:
Output: [1] Jazz Rock Pop Classic Pop Jazz Rock Jazz Levels: Classic Jazz Pop Rock
Output: [1] Jazz Rock Pop Jazz Pop Classic Rock Jazz Levels: Classic Jazz Pop Rock
1.13 Data Frames
Data Frames in R Language are generic data objects of R that are used to store tabular data. Data frames can also be interpreted as matrices where each column of a matrix can be of different data types. R DataFrame is made up of three principal components, the data, rows, and columns. A data frame is a two-dimensional array-like structure or a table in which a column contains values of one variable, and rows contains one set of values from each column. A data frame is a special case of the list in which each component has equal length.A matrix can contain one type of data, but a data frame can contain different data types such as numeric, character, factor, etc.
42
CHAPTER 1.
INTRODUCTION TO R
The following are characteristics of a data frame.
The columns name should be non-empty.
The rows name should be unique.
The data which is stored in a data frame can be a factor, numeric, or character type.
Each column contains the same number of data items.
1.13.1 Creating a data frame
To create a data frame, we can call data.frame() and supply the data of each column by a vector of the corresponding type. Each row in a data frame is called a record, and each column is a variable.
Examples:
1. emp.data <−data.f rame( empid = c(1 : 5),
empname = c(”Rick”, ”Dan”, ”Michelle”, ”Ryan”, ”Gary”), salary = c(623.3, 515.2, 611.0, 729.0, 843.25),
startdate = as.Date(c(”2012 − 01 − 01”, ”2013 − 09 − 23”, ”2014 − 11 −
15”, ”2014 − 05 − 11”, ”2015 − 03 − 27”)),
)
1.13. DATA FRAMES
43
print(emp.data)
Output:
2. mydata <−data.f rame(person = c(”Peter”, ”Lois”, ”Meg”, ”Chris”, ”Stewie”), age = c(42, 40, 17, 14, 1),
sex = factor(c(”M ”, ”F ”, ”F ”, ”M ”, ”M ”)))
print(mydata)
Output:
3. persons <−data.f rame(Name = c(”Ken”, ”Ashley”, ”Jennifer”), Gender = c(”Male”, ”Female”, ”Female”),
Age = c(24, 25, 23),
Major = c(”Finance”, ”Statistics”, ”ComputerScience”)) persons
Output:
4. Other than creating a data frame from raw data, we can also create it from a list by calling either data.frame directly or as.data.frame.
l1 <−list(x = c(2.5, 3.6, 4.9), y = c(”a”, ”b”, ”c”))
44
CHAPTER 1. INTRODUCTION TO R
data.frame(l1) (or) as.data.frame(l1) Output:
x y
1 2.5 a
2 3.6 b
3 4.9 c
5. We can also create a data frame from a matrix with the same method. m1 <−matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, byrow = FALSE) data.frame(m1)
(or) as.data.frame(m1) Output:
X1 | X2 | X3 |
1 1 | 4 | 7 |
2 2 | 5 | 8 |
3 3 | 6 | 9 |
1.13.2 Naming rows and columns
Since a data frame is a list but also looks like a matrix, the ways we access these two types of objects both apply to a data frame.
Example
df 1 <−data.f rame(id = 1 : 5, x = c(0, 2, 1, −1, −3), y = c(0.5, 0.2, 0.1, 0.5, 0.9))
df 1
Output:
id | x | y |
1 1 | 0 | 0.5 |
2 2 | 2 | 0.2 |
3 3 | 1 | 0.1 |
4 4 | -1 | 0.5 |
5 5 | 3 | 0.9 |
colnames(df 1) <−c(”id”, ”level”, ”score”) rownames(df 1) < −letters[1 : 5]
df 1
Output:
1.13. DATA FRAMES
45
id | level | score |
a 1 | 0 | 0.5 |
b 2 | 2 | 0.2 |
c 3 | 1 | 0.1 |
d 4 | -1 | 0.5 |
e 5 | 3 | 0.9 |
1.13.3 Subsetting a data frame
The data of the data frame is very crucial for us. To manipulate the data of the data frame, it is essential to extract it from the data frame. We can extract the data in three ways which are as follows:
We can extract the specific columns from a data frame using the column name along with $ (or) use [[]] to do so by position.
Examples:
1. emp.data$emp name
Output:
[1] ”Rick” ”Dan” ”Michelle” ”Ryan” ”Gary”
Output:
[1] 42 40 17 14 1
Output:
[1] Male Female Female Levels: Female Male
We can extract the specific rows also from a data frame.
Examples:
1. emp.data[2 : 3, ]
Output:
emp id emp name
salary start date
515.2 2013 − 09 − 23
611.0 2014 − 11 − 15
2
3
2. mydata[1, ]]
Output:
person
1 Peter
age sex
42 M
We can extract the specific rows corresponding to specific columns.
Examples:
46
CHAPTER 1. INTRODUCTION TO R
| emp name | start date |
1 | Rick | 2012-01-01 |
4 | Ryan | 2014-05-11 |
5 | Gary | 2015-03-27 |
Output:
[1] 515.2
Output:
[1] M
Levels: F M
3. persons[3, 3]
Output:
[1] 23
Filtering data: The data in a dataframe can be filtered by imposing condi-tions using logical operators.
Example:
emp.data[emp.data$salary >= 620.00, c(”emp name”, ”start date”)] Output:
We can also filter the rows of a dataframe by a criterion that the row name must be among a certain names.
Example:
emp.data[rownames(emp.data)%in%c(1, 3, 5), c(”emp name”, ”salary”, ”start date”)] Output:
emp name
1 Rick
3 Michelle
5 Gary
salary 623.30
611.00
843.25
start date
2012-01-01
2014-11-15
2015-03-27
1.13.4 Adding Data Columns and new records
We can add data to an existing data frame. This could be a set of obser-vations for a new variable (adding to the number of columns), or it could be more records (adding to the number of rows). The rbind and cbind functions can be used to append rows and columns, respectively.
Examples:
1. newrecord <−data.f rame(person = ”Brian”, age = 7, sex = factor(”M ”, levels = levels(mydata$sex)))
mydata < −rbind(mydata, newrecord)
1.13. DATA FRAMES
47
2. Adding a variable to a data frame is also quite straightforward. If we need to include a given data on the classification of how funny these six individ-uals are, defined as a “degree of funniness,” can be done by cbind. The degree of funniness can take three possible values: Low, Med (medium), and High.
funny <−c(”High”, ”High”, ”Low”, ”Med”, ”High”, ”Med”) funny <−f actor(x = funny, levels = c(”Low”, ”Med”, ”High”)) funny
Output:
[1] High High Low Med High Med
Levels: Low Med High mydata <−cbind(mydata, funny) mydata
Output:
3. The rbind and cbind functions aren’t the only ways to extend a data frame. One useful alternative for adding a variable is to use the dollar operator, much like adding a new member to a named list.
Example:
mydata$age.mon <−mydata$age ∗ 12 mydata Output:
48
CHAPTER 1. INTRODUCTION TO R
1.13.5 Setting values as a list and a Matrix
We can assign new values to a list member using $ and < − together.
Example:
df 1$score <−c(0.6, 0.3, 0.2, 0.4, 0.8)
df 1 Alternatively, [] works too, and it also allows multiple changes in one expression in contrast to [[]], which only allows modifying one column at a time. Example:
df 1[”score”] <−c(0.8, 0.5, 0.2, 0.4, 0.8)
df 1
df 1[[”score”]] <−c(0.4, 0.5, 0.2, 0.8, 0.4)
df 1
df 1[c(”level”, ”score”)] <−list(level = c(1, 2, 1, 0, 0), score = c(0.1, 0.2, 0.3, 0.4, 0.5))
df 1
Setting values as a matrix
Using list notations to set values of a data frame has the same problem as sub-setting, we can only access the columns. If we need to set values with more flexibility, we can use matrix notations.
Example:
df 1