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

Module I

R is a programming language designed for statistical computing and data analysis, favored for its open-source nature and extensive package repository. It is widely used across various industries, including finance and healthcare, for tasks such as data analysis and machine learning. The document also outlines R's data structures, including vectors, matrices, lists, and data frames, and provides insights into vector operations and indexing.

Uploaded by

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

Module I

R is a programming language designed for statistical computing and data analysis, favored for its open-source nature and extensive package repository. It is widely used across various industries, including finance and healthcare, for tasks such as data analysis and machine learning. The document also outlines R's data structures, including vectors, matrices, lists, and data frames, and provides insights into vector operations and indexing.

Uploaded by

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

Module I

R Programming Language - Introduction

R is a programming language and software environment that has become the first
choice for statistical computing and data analysis. Developed in the early 1990s by
Ross Ihaka and Robert Gentleman, R was built to simplify complex data manipulation
and create clear, customizable visualizations. Over time, it has gained popularity among
statisticians, data scientists and researchers because of its capabilities and the vast
array of packages available.

As data-driven decision-making has grown, R has established itself as an important


tool in various industries, including finance and healthcare, due to its ability to handle
large datasets and perform in-depth statistical analysis.

Why Choose R Programming?


R is a unique language that offers a wide range of features for data analysis, making it
an essential tool for professionals in various fields. Here’s why R is preferred:

● Free and Open-Source: R is open to everyone, meaning users can modify,


share and distribute their work freely.
● Designed for Data: R is built for data analysis, offering a comprehensive set
of tools for statistical computing and graphics.
● Large Package Repository: The Comprehensive R Archive Network (CRAN)
offers thousands of add-on packages for specialized tasks.
● Cross-Platform Compatibility: R can work on Windows, Mac and Linux
operating systems.
● Great for Visualization: With packages like ggplot2, R makes it easy to
create informative, interactive charts and plots.

Applications of R
R is used in a variety of fields, including:

● Data Science and Machine Learning: R is widely used for data analysis,
statistical modeling and machine learning tasks.
● Finance: Financial analysts use R for quantitative modeling and risk analysis.
● Healthcare: In clinical research, R helps analyze medical data and test
hypotheses.
● Academia: Researchers and statisticians use R for data analysis and
publishing reproducible research.

R Data Structures

R has a variety of data structures. Here, we will sketch some of the most frequently
used structures to give you an overview of R before we dive into the details. This way,
you can at least get started with some meaningful examples, even if the full story
behind them must wait.

[Link], the R Workhorse

The vector type is really the heart of R. It’s hard to imagine R code, or even an
interactive R session, that doesn’t involve vectors. The elements of a vector must all
have the same mode, or data type. You can have a vector consisting of three character
strings (of mode character) or three integer elements (of mode integer), but not a
vector with one integer element and two character string elements

Scalars
Scalars, or individual numbers, do not really exist in R. As mentioned earlier, what
appear to be individual numbers are actually one-element vectors. Consider the
following:

> x <- 8

>x

[1] 8

Recall that the [1] here signifies that the following row of numbers begins with
element 1 of a vector—in this case, x[1]. So you can see that R was indeed treating x
as a vector, albeit a vector with just one element

Character Strings

Character strings are actually single-element vectors of mode character, (rather than
mode numeric):

In the first example, we create a vector x of numbers, thus of mode numeric. Then we
create two vectors of mode character: y is a one-element (that is, one-string) vector,
and z consists of two strings. R has various string-manipulation functions. Many deal
with putting strings together or taking them apart, such as the two shown here:
Matrices

An R matrix corresponds to the mathematical concept of the same name: a rectangular


array of numbers. Technically, a matrix is a vector, but with two additional attributes:
the number of rows and the number of columns. Here is some sample matrix code:

Lists

Like an R vector, an R list is a container for values, but its contents can be items of
different data types. (C/C++ programmers will note the analogy to a C struct.) List
elements are accessed using two-part names, which are indicated with the dollar sign
$ in R. Here’s a quick example:

Data Frames

A typical data set contains data of different modes. In an employee data set, for
example, we might have character string data, such as employee names, and numeric
data, such as salaries. So, although a data set of (say) 50 employees with 4 variables
per worker has the look and feel of a 50-by-4 matrix, it does not qualify as such in R,
because it mixes types. Instead of a matrix, we use a data frame. A data frame in R is a
list, with each component of the list being a vector corresponding to a column in our
“matrix” of data. Indeed, you can create data frames in just this way

Classes

R is an object-oriented language. Objects are instances of classes. Classes are a bit


more abstract than the data types you’ve met so far. Here, we’ll look briefly at the
concept using R’s S3 classes. (The name stems from their use in the old S language,
version 3, which was the inspiration for R.) Most of R is based on these classes, and
they are exceedingly simple. Their instances are simply R lists but with an extra
attribute: the class name. For example, we noted earlier that the (nongraphical) output
of the hist() histogram function is a list with various components, such as break and
count components. There was also an attribute, which specified the class of the list,
namely histogram.

The help() Function

To get online help, invoke help(). For example, to get information on the seq() function,
type this:
> help(seq)

The shortcut to help() is a question mark (?):

> ?seq

Special characters and some reserved words must be quoted when used with the
help() function. For instance, you need to type the following to get help on the <
operator:

> ?"<"

And to see what the online manual has to say about for loops, enter this:

> ?"for"

You can use the function [Link]() to do a Google-style search through R’s
documentation. For instance, say you need a function to generate random variates from
multivariate normal distributions. To determine which function, if any, does this, you
could try something like this:

> [Link]("multivariate normal")

Help for Batch Mode Recall that R has batch commands that allow you to run a
command directly from your operating system’s shell. To get help on a particular batch
command, you can type:

R CMD command --help

For example, to learn all the options associated with the INSTALL command
(discussed in Appendix B), you can type this:

R CMD INSTALL --help

Scalars, Vectors

In many programming languages, vector variables are considered different from


scalars, which are single-number variables. Consider the following C code, for
example:
int x;

int y[3];

This requests the compiler to allocate space for a single integer named x and a three-
element integer array (C terminology analogous to R’s vector type) named y. But in R,
numbers are actually considered one-element vectors, and there is really no such thing
as a scalar. R variable types are called modes. Recall from Chapter 1 that all elements
in a vector must have the same mode, which can be integer, numeric (floating-point
number), character (string), logical (Boolean), complex, and so on. If you need your
program code to check the mode of a variable x, you can query it by the call typeof(x).
Unlike vector indices in ALGOL-family languages, such as C and Python, vector indices
in R begin at 1.

Obtaining the Length of a Vector

You can obtain the length of a vector by using the length() function:

Matrices and Arrays as Vectors

Arrays and matrices (and even lists, in a sense) are actually vectors too, as you’ll see.
They merely have extra class attributes. For example, matrices have the number of
rows and columns. We’ll discuss them in detail in the next chapter, but it’s worth
noting now that arrays and matrices are vectors, and that means that everything we
say about vectors applies to them, too. Consider the following example:

The 2-by-2 matrix m is stored as a four-element vector, column-wise, as (1,3,2,4). We


then added (10,11,12,13) to it, yielding (11,14,14,17), but R remembered that we were
working with matrices and thus gave the 2-by-2 result you see in the example.
Declarations

Typically, compiled languages require that you declare variables; that is, warn the
interpreter/compiler of the variables’ existence before using them. This is the case in
our earlier C example: int x; int y[3];

As with most scripting languages (such as Python and Perl), you do not declare
variables in R.

For instance, consider this code:

z <- 3

This code, with no previous reference to z, is perfectly legal (and commonplace).


However, if you reference specific elements of a vector, you must warn R. For instance,
say we wish y to be a two-component vector with values 5 and 12. The following will
not work:

> y[1] <- 5

> y[2]

<- 12

This approach is all right because on the right-hand side we are creating a new vector,
to which we then bind y.

Recycling

When applying an operation to two vectors that requires them to be the same length,
R automatically recycles, or repeats, the shorter one, until it is long enough to match
the longer one. Here is an example:

The shorter vector was recycled, so the operation was taken to be as follows:

>c(1,2,4,1,2) + c(6,0,9,20,22)
Here’s a more subtle example:

Again, keep in mind that matrices are actually long vectors. Here, x, as a 3-by-2 matrix,
is also a six-element vector, which in R is stored column by column. In other words, in
terms of storage, x is the same as c(1,2,3,4,5,6). We added a two-element vector to
this six-element one, so our added vector needed to be repeated twice to make six
elements. In other words, we were essentially doing this:

x + c(1,2,1,2,1,2)

Not only that, but c(1,2,1,2,1,2) was also changed from a vector to a matrix having the
same shape as x before the addition took place:

12

21

12

Common Vector Operations

Vector Operations in R (Overview)

● Covers vector arithmetic & logical operations, vector indexing, and ways to
create vectors
● Includes extended examples of these operations
1. Vector Arithmetic and Logical Operations

● R is a functional language: operators are functions

2+3

"+"(2, 3)

● Scalars are one-element vectors


● Vector arithmetic is element-wise

x <- c(1,2,4)

x + c(5,0,-1) # addition

x * c(5,0,-1) # multiplication (not matrix product)

x / c(5,4,-1) # division

x %% c(5,4,-1) # modulus

● Each operation applies to corresponding elements


● Single values may be recycled to match vector length

2.4.2 Vector Indexing

Syntax: vector1[vector2]

● Extract elements using indices

y <- c(1.2,3.9,0.4,0.12)

y[c(1,3)]

y[2:3]

v <- 3:4

y[v]
● Duplicate indices allowed

x <- c(4,2,17,5)

x[c(1,1,3)]

● Negative indices exclude elements

z <- c(5,12,13)

z[-1]

z[-1:-2]

● Use length() for general indexing

z[1:(length(z)-1)]

z[-length(z)]

● More flexible than hard-coded indices

2.4.3 Generating Vectors with : Operator


● : creates a sequence of integers

5:8

5:1

● Commonly used in loops

for (i in 1:length(x)) { }

● Operator precedence warning

i <- 2

1:i-1 # interpreted as (1:i) - 1 recycling

1:(i-1) # correct range


● : has higher precedence than -
● Recycling occurs when vector lengths differ

2.4.4 Generating Sequences with seq()

seq() generalizes :

● Supports custom spacing and lengths

seq(from=12, to=30, by=3)

seq(from=1.1, to=2, length=10)

● Useful for avoiding empty-vector loop problems

for (i in seq(x)) { }

● Behavior comparison:

x <- c(5,12,13)

seq(x)

x <- NULL

seq(x)

● seq(x) = 1:length(x) when nonempty


● Returns NULL when x
is empty zero iterations

2.4.5 Repeating Vectors with rep()


● Syntax: rep(x, times)

● Creates times × length(x) elements

rep(8,4)

rep(c(5,12,13),3)

rep(1:3,2)

● each argument repeats individual elements

rep(c(5,12,13), each=2)

● Useful for constructing long or patterned vectors

Using all() and any()

The any() and all() functions are handy shortcuts. They report whether any or all of
their arguments are TRUE.
The any() function then reports whether any of those values is TRUE. The all() function
works similarly and reports if all of the values are TRUE.

You might also like