R Programming Unit I Notes
R Programming Unit I Notes
D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
UNIT I
Introduction to R
3. Click on "install R for the first time" link to download the R executable (.exe) file.
4. Run the R executable file to start installation, and allow the app to make changes to your
device.
R has now been successfully installed on your Windows OS. Open the R GUI to start writing R
codes.
RStudio is now successfully installed on your computer. The RStudio Desktop IDE interface is
shown in the figure below:
R - Variables
A variable provides us with named storage that our programs can manipulate. A variable in R
can store an atomic vector, group of atomic vectors or a combination of many Robjects. A valid
variable name consists of letters, numbers and the dot or underline characters. The variable name
starts with a letter or the dot not followed by a number.
var_name% Invalid Has the character '%'. Only dot(.) and underscore allowed.
.var_name, Can start with a dot(.) but the dot(.)should not be followed by a
valid
var.name number.
Variable Assignment
The variables can be assigned values using leftward, rightward and equal to operator. The values
of the variables can be printed using print() or cat() function. The cat() function combines
multiple items into a continuous print output.
Live Demo
# Assignment using equal operator.
var.1 = c(0,1,2,3)
print(var.1)
cat ("var.1 is ", var.1 ,"\n")
cat ("var.2 is ", var.2 ,"\n")
cat ("var.3 is ", var.3 ,"\n")
[1] 0 1 2 3
var.1 is 0 1 2 3
var.2 is learn R
var.3 is 1 1
Constants in R: -
Constants are those entities whose values aren't meant to be changed anywhere throughout the
code. In R, we can declare constants using the <- symbol. For example,
Output
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Types of R Constants:-
1) Integer Constants:-
Integer constants are the integer values we use in our code. These constants end with the letter L.
For example,
x <- 15L
print(typeof(x))
print(class(x))
Output:
[1] "integer"
[1] "integer"
Here, 15L is a constant which has been assigned to x. You can see that the type and class of the
constant is integer.
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
2. Numeric Constants:-
z <- 3e-3
print(z) # 0.003
print(class(z)) # "numeric"
y <- 3.4
print(y) # 3.4
print(class(z)) # "numeric"
Output:
[1] 0.003
[1] "numeric"
[1] 3.4
[1] "numeric"
3. Logical Constants:-
x <- TRUE
y <- FALSE
print(x)
print(y)
Output:-
[1] TRUE
[1] FALSE
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
4. String Constants:-
String constants are the string data we use in our code. For example,
Output:
5. Complex Constants:-
A complex constant is data that contains a real and an imaginary part (denoted by the suffix i).
For example,
y <- 3.2e-1i
print(y)
print(typeof(y))
Output:
[1] 0+0.32i
[1] "complex"
Special R Constants:-
b) x <- NULL
c) print(x) # NULL
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
print(typeof(x)) # "NULL"
a <- 2^2020
print(a) # Inf
print(b) # -Inf
e) print(0/0) # NaN
print(Inf/Inf) # NaN
print(NA + 20) # NA
R - Data Types
Generally, while doing programming in any programming language, you need to use various
variables to store various information. Variables are nothing but reserved memory locations to
store values. This means that, when you create a variable, you reserve some space in memory.
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
You may like to store information of various data types like character, wide character, integer,
floating point, double floating point, Boolean etc. Based on the data type of a variable, the
operating system allocates memory and decides what can be stored in the reserved memory.
In contrast to other programming languages like C and java in R, the variables are not declared
as some data type. The variables are assigned with R-Objects and the data type of the R-object
becomes the data type of the variable. There are many types of R-objects. The frequently used
ones are −
Vectors
Lists
Matrices
Arrays
Factors
Data Frames
The simplest of these objects is the vector object and there are six data types of these atomic
vectors, also termed as six classes of vectors. The other R-Objects are built upon the atomic
vectors.
Live Demo
v <- TRUE
Logical TRUE, FALSE print(class(v))
it produces the following result −
[1] "logical"
Live Demo
v <- 23.5
Numeric 12.3, 5, 999 print(class(v))
it produces the following result −
[1] "numeric"
Live Demo
v <- 2L
Integer 2L, 34L, 0L print(class(v))
it produces the following result −
[1] "integer"
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Live Demo
v <- 2+5i
Complex 3 + 2i print(class(v))
it produces the following result −
[1] "complex"
Live Demo
v <- "TRUE"
Character 'a' , '"good", "TRUE", '23.4' print(class(v))
it produces the following result −
[1] "character"
Live Demo
v <- charToRaw("Hello")
Raw "Hello" is stored as 48 65 6c 6c 6f print(class(v))
it produces the following result −
[1] "raw"
In R programming, the very basic data types are the R-objects called vectors which hold
elements of different classes as shown above. Please note in R the number of classes is not
confined to only the above six types. For example, we can use many atomic vectors and create an
array whose class will become array.
Vectors
When you want to create vector with more than one element, you should use c() function which
means to combine the elements into a vector.
Live Demo
# Create a vector.
apple <- c('red','green',"yellow")
print(apple)
Lists
A list is an R-object which can contain many different types of elements inside it like vectors,
functions and even another list inside it.
Live Demo
# Create a list.
list1 <- list(c(2,5,3),21.3,sin)
[[1]]
[1] 2 5 3
[[2]]
[1] 21.3
[[3]]
function (x) .Primitive("sin")
Matrices
A matrix is a two-dimensional rectangular data set. It can be created using a vector input to the
matrix function.
Live Demo
# Create a matrix.
M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
print(M)
Arrays
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
While matrices are confined to two dimensions, arrays can be of any number of dimensions. The
array function takes a dim attribute which creates the required number of dimension. In the
below example we create an array with two elements which are 3x3 matrices each.
Live Demo
# Create an array.
a <- array(c('green','yellow'),dim = c(3,3,2))
print(a)
,,1
,,2
Factors
Factors are the r-objects which are created using a vector. It stores the vector along with the
distinct values of the elements in the vector as labels. The labels are always character irrespective
of whether it is numeric or character or Boolean etc. in the input vector. They are useful in
statistical modeling.
Factors are created using the factor() function. The nlevels functions gives the count of levels.
Live Demo
# Create a vector.
apple_colors <- c('green','green','yellow','red','red','red','green')
Data Frames
Data frames are tabular data objects. Unlike a matrix in data frame each column can contain
different modes of data. The first column can be numeric while the second column can be
character and third column can be logical. It is a list of vectors of equal length.
Live Demo
# Create the data frame.
BMI <- data.frame(
gender = c("Male", "Male","Female"),
height = c(152, 171.5, 165),
weight = c(81,93, 78),
Age = c(42,38,26)
)
print(BMI)
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. R language is rich in built-in operators and provides following types of operators.
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Types of Operators
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Miscellaneous Operators
Arithmetic Operators
Following table shows the arithmetic operators supported by R language. The operators act on
each element of the vector.
Live Demo
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
+ Adds two vectors print(v+t)
it produces the following result −
[1] 10.0 8.5 10.0
Live Demo
v <- c( 2,5.5,6)
Subtracts second vector from t <- c(8, 3, 4)
− print(v-t)
the first
it produces the following result −
[1] -6.0 2.5 2.0
Live Demo
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
* Multiplies both vectors print(v*t)
it produces the following result −
[1] 16.0 16.5 24.0
Live Demo
Divide the first vector with the
/ v <- c( 2,5.5,6)
second
t <- c(8, 3, 4)
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
print(v/t)
When we execute the above code, it produces the
following result −
[1] 0.250000 1.833333 1.500000
Live Demo
v <- c( 2,5.5,6)
Give the remainder of the first t <- c(8, 3, 4)
%% print(v%%t)
vector with the second
it produces the following result −
[1] 2.0 2.5 2.0
Live Demo
v <- c( 2,5.5,6)
The result of division of first t <- c(8, 3, 4)
%/% print(v%/%t)
vector with second (quotient)
it produces the following result −
[1] 0 1 1
Live Demo
v <- c( 2,5.5,6)
The first vector raised to the t <- c(8, 3, 4)
^ print(v^t)
exponent of second vector
it produces the following result −
[1] 256.000 166.375 1296.000
Relational Operators
Following table shows the relational operators supported by R language. Each element of the
first vector is compared with the corresponding element of the second vector. The result of
comparison is a Boolean value.
Live Demo
Checks if each element of the first vector v <- c(2,5.5,6,9)
> is greater than the corresponding element t <- c(8,2.5,14,9)
of the second vector. print(v>t)
it produces the following result −
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Live Demo
v <- c(2,5.5,6,9)
Checks if each element of the first vector t <- c(8,2.5,14,9)
< is less than the corresponding element of print(v < t)
the second vector.
it produces the following result −
[1] TRUE FALSE TRUE FALSE
Live Demo
v <- c(2,5.5,6,9)
Checks if each element of the first vector t <- c(8,2.5,14,9)
== is equal to the corresponding element of print(v == t)
the second vector.
it produces the following result −
[1] FALSE FALSE FALSE TRUE
Live Demo
v <- c(2,5.5,6,9)
Checks if each element of the first vector t <- c(8,2.5,14,9)
<= is less than or equal to the corresponding print(v<=t)
element of the second vector.
it produces the following result −
[1] TRUE FALSE TRUE TRUE
Live Demo
Checks if each element of the first vector v <- c(2,5.5,6,9)
is greater than or equal to the t <- c(8,2.5,14,9)
>= print(v>=t)
corresponding element of the second
vector. it produces the following result −
[1] FALSE TRUE FALSE TRUE
Live Demo
v <- c(2,5.5,6,9)
Checks if each element of the first vector t <- c(8,2.5,14,9)
!= is unequal to the corresponding element print(v!=t)
of the second vector.
it produces the following result −
[1] TRUE TRUE TRUE FALSE
Logical Operators
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Following table shows the logical operators supported by R language. It is applicable only to
vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical
value TRUE.
Each element of the first vector is compared with the corresponding element of the second
vector. The result of comparison is a Boolean value.
Live Demo
It is called Element-wise Logical AND operator. v <- c(3,1,TRUE,2+3i)
It combines each element of the first vector with t <- c(4,1,FALSE,2+3i)
& the corresponding element of the second vector print(v&t)
and gives a output TRUE if both the elements are
it produces the following result −
TRUE.
[1] TRUE TRUE FALSE TRUE
Live Demo
It is called Element-wise Logical OR operator. It v <- c(3,0,TRUE,2+2i)
combines each element of the first vector with the t <- c(4,0,FALSE,2+3i)
| corresponding element of the second vector and print(v|t)
gives a output TRUE if one the elements is
it produces the following result −
TRUE.
[1] TRUE FALSE TRUE TRUE
Live Demo
It is called Logical NOT operator. Takes each v <- c(3,0,TRUE,2+2i)
! element of the vector and gives the opposite print(!v)
logical value. it produces the following result −
[1] FALSE TRUE FALSE FALSE
The logical operator && and || considers only the first element of the vectors and give a vector of
single element as output.
Live Demo
v <- c(3,0,TRUE,2+2i)
Called Logical AND operator. Takes first element of both the vectors
&& t <- c(1,3,TRUE,2+3i)
and gives the TRUE only if both are TRUE.
print(v&&t)
it produces the following r
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
[1] TRUE
Live Demo
v <- c(0,0,TRUE,2+2i)
Called Logical OR operator. Takes first element of both the vectors t <- c(0,3,TRUE,2+3i)
|| print(v||t)
and gives the TRUE if one of them is TRUE.
it produces the following r
[1] FALSE
Assignment Operators
Live Demo
v1 <- c(3,1,TRUE,2+3i)
v2 <<- c(3,1,TRUE,2+3i)
v3 = c(3,1,TRUE,2+3i)
<−
print(v1)
or
print(v2)
= Called Left Assignment
print(v3)
or
<<− it produces the following result −
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i
Live Demo
c(3,1,TRUE,2+3i) -> v1
c(3,1,TRUE,2+3i) ->> v2
-> print(v1)
or Called Right Assignment print(v2)
->> it produces the following result −
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i
Miscellaneous Operators
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
These operators are used to for specific purpose and not general mathematical or logical
computation.
Live Demo
v1 <- 8
v2 <- 12
This operator is t <- 1:10
used to identify if print(v1 %in% t)
%in%
an element belongs print(v2 %in% t)
to a vector. it produces the following result −
[1] TRUE
[1] FALSE
Live Demo
M = matrix( c(2,6,5,1,10,4), nrow = 2,ncol = 3,byrow = TRUE)
t = M %*% t(M)
This operator is
print(t)
used to multiply a
%*% it produces the following result −
matrix with its
transpose. [,1] [,2]
[1,] 65 82
[2,] 82 117
Developers often have a need to interact with users, either to get data or to provide some sort
of result. Most programs today use a dialog box as a way of asking the user to provide some
type of input. Like other programming languages in R it’s also possible to take input from the
user. For doing so, there are two methods in R.
In R language readline() method takes input in string format. If one inputs an integer then it is
inputted as a string, lets say, one wants to input 255, then it will input as “255”, like a string.
So one needs to convert that inputted value to the format that he needs. In this case,
string “255” is converted to integer 255. To convert the inputted value to the desired data type,
there are some functions in R,
Syntax:
print(var)
Output:-
Another way to take user input in R language is using a method, called scan() method. This
method takes input from the console. This method is a very handy method while inputs are
needed to taken quickly for any mathematical calculation or for any dataset. This method reads
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
data in the form of a vector or list. This method also uses to reads input from a file also.
Syntax:-
x = scan()
scan() method is taking input continuously, to terminate the input process, need to
press Enter key 2 times on the console.
Example:-
This is simple method to take input using scan() method, where some integer number is taking
as input and print those values in the next line on the console.
x = scan()
print(x)
Output:-
1: 1 2 3 4 5 6
7: 7 8 9 4 5 6
13:
Read 12 items
[1] 1 2 3 4 5 6 7 8 9 4 5 6
R Built-in Functions:-
The functions which are already created or defined in the programming framework are known as
a built-in function. R has a rich set of functions that can be used to perform almost every task for
the user. These built-in functions are divided into the following categories based on their
functionality.
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
i) Math Functions:-
R provides the various mathematical functions to perform the mathematical calculation. These
mathematical functions are very helpful to find absolute value, square value and much more
calculations. In R, there are the following functions which are used:
3. ceiling(x) It returns the smallest integer which is larger than x<- 4.5
or equal to x. print(ceiling(x))
Output: [1] 5
4. floor(x) It returns the largest integer, which is smaller than x<- 2.5
or equal to x. print(floor(x))
Output: [1] 2
R provides various string functions to perform tasks. These string functions allow us to extract sub
string from string, search pattern etc. There are the following string functions in R:
R provides various statistical probability functions to perform statistical task. These statistical
functions are very helpful to find normal density, normal quantile and many more calculation. In
R, there are following functions which are used:
1. dnorm(x, m=0, sd=1, It is used to find the height of the a <- seq(-7, 7, by=0.1)
log=False) probability distribution at each b <- dnorm(a, mean=2.5, sd=0.5)
point to a given mean and png(file="dnorm.png")
standard deviation plot(x,y)
dev.off()
2. pnorm(q, m=0, sd=1, it is used to find the probability a <- seq(-7, 7, by=0.2)
lower.tail=TRUE, of a normally distributed random b <- dnorm(a, mean=2.5, sd=2)
log.p=FALSE) numbers which are less than the png(file="pnorm.png")
value of a given number. plot(x,y)
dev.off()
3. qnorm(p, m=0, sd=1) It is used to find a number whose a <- seq(1, 2, by=002)
cumulative value matches with b <- qnorm(a, mean=2.5, sd=0.5)
the probability value. png(file="qnorm.png")
plot(x,y)
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
dev.off()
5. dbinom(x, size, prob) It is used to find the probability a<-seq(0, 40, by=1)
density distribution at each b<- dbinom(a, 40, 0.5)
point. png(file="pnorm.png")
plot(x,y)
dev.off()
6. pbinom(q, size, prob) It is used to find the cumulative a <- pbinom(25, 40,0.5)
probability (a single value print(a)
representing the probability) of Output
an event. [1] 0.9596548
7. qbinom(p, size, prob) It is used to find a number whose a <- qbinom(0.25, 40,01/2)
cumulative value matches the print(a)
probability value. Output
[1] 18
12. dunif(x, min=0, max=1) This function provide dunif(x, min=0, max=1,
information about the uniform log=FALSE)
distribution on the interval from
min to max. It gives the density.
13. punif(q, min=0, max=1) It gives the distributed function punif(q, min=0, max=1,
lower.tail=TRUE,
log.p=FALSE)
14. qunif(p, min=0, max=1) It gives the quantile function. qunif(p, min=0, max=1,
lower.tail=TRUE,
log.p=FALSE)
15. runif(x, min=0, max=1) It generates random deviates. runif(x, min=0, max=1)
Apart from the functions mentioned above, there are some other useful functions which helps for
statistical purpose. There are the following functions:
1. mean(x, trim=0, It is used to find the mean for x object a<-c(0:10, 40)
na.rm=FALSE) xm<-mean(a)
print(xm)
Output:[1] 7.916667
Vectors: -
To combine the list of items to a vector, use the c() function and separate the items by a comma.
In the example below, we create a vector variable called fruits, that combine strings:
Example 1)
# Vector of strings
fruits <- c("banana", "apple", "orange")
# Print fruits
fruits
Output: -
[1] "banana" "apple" "orange"
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Example 2)
# Vector of numerical values
numbers <- c(1, 2, 3)
# Print numbers
numbers
Output: -
[1] 1 2 3
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. Indexing will be performed with the help of integer,
character, or logic.
On integer vector, indexing is performed in the same way as we have applied in C, C++, and java.
There is only one difference, i.e., in C, C++, and java the indexing starts from 0, but in R, the
indexing starts from 1. Like other programming languages, we perform indexing by specifying an
integer value in square braces [] next to our vector.
Example:-
1. seq_vec<-seq(1,4,length.out=6)
2. seq_vec
3. seq_vec[2]
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Output:-
In character vector indexing, we assign a unique key to each element of the vector. These keys are
uniquely defined as each element and can be accessed very easily. Let's see an example to
understand how it is performed.
Example:-
1. char_vec<-c("shubham"=22,"arpita"=23,"vaishali"=25)
2. char_vec
3. char_vec["arpita"]
Output:-
In logical indexing, it returns the values of those positions whose corresponding position has a
logical vector TRUE. Let see an example to understand how it is performed on vectors.
Example:-
1. a<-c(1,2,3,4,5,6)
2. a[c(TRUE,FALSE,TRUE,TRUE,FALSE,TRUE)]
Output:-
[1] 1 3 4 6
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Vector Operations:-
In R, there are various operation which is performed on the vector. We can add, subtract, multiply
or divide two or more vectors from each other. In data science, R plays an important role, and
operations are required for data manipulation. There are the following types of operation which
are performed on the vector.
1) Combining vectors:-
The c() function is not only used to create a vector, but also it is also used to combine two vectors.
By combining one or more vectors, it forms a new vector which contains all the elements of each
vector. Let see an example to see how c() function combines the vectors.
Example:-
1. p<-c(1,2,4,5,7,8)
2. q<-c("shubham","arpita","nishka","gunjan","vaishali","sumit")
3. r<-c(p,q)
Output
2) Arithmetic operations:-
We can perform all the arithmetic operation on vectors. The arithmetic operations are performed
member-by-member on vectors. We can add, subtract, multiply, or divide two vectors. Let see an
example to understand how arithmetic operations are performed on vectors.
Example:-
1. a<-c(1,3,5,7)
2. b<-c(2,4,6,8)
3. a+b
4. a-b
5. a/b
6. a%%b
Output:-
[1] 3 7 11 15
[1] -1 -1 -1 -1
[1] 2 12 30 56
[1] 0.5000000 0.7500000 0.8333333 0.8750000
[1] 1 3 5 7
3) Logical Index vector:-
With the help of the logical index vector in R, we can form a new vector from a given vector. This
vector has the same length as the original vector. The vector members are TRUE only when the
corresponding members of the original vector are included in the slice; otherwise, it will be false.
Let see an example to understand how a new vector is formed with the help of logical index vector.
Example:
1. a<-c("Shubham","Arpita","Nishka","Vaishali","Sumit","Gunjan")
2. b<-c(TRUE,FALSE,TRUE,TRUE,FALSE,FALSE)
3. a[b]
Output:
4) Numeric Index:-
In R, we specify the index between square braces [ ] for indexing a numerical value. If our index
is negative, it will return us all the values except for the index which we have specified. For
example, specifying [-3] will prompt R to convert -3 into its absolute value and then search for the
value which occupies that index.
Example:
1. q<-c("shubham","arpita","nishka","gunjan","vaishali","sumit")
2. q[2]
3. q[-4]
4. q[15]
Output:
[1] "arpita"
[1] "shubham" "arpita" "nishka" "vaishali" "sumit"
[1] NA
5) Duplicate Index:-
An index vector allows duplicate values which means we can access one element twice in one
operation. Let see an example to understand how duplicate index works.
Example:
1. q<-c("shubham","arpita","nishka","gunjan","vaishali","sumit")
2. q[c(2,4,4,3)]
Output:
Range index is used to slice our vector to form a new vector. For slicing, we used colon(:) operator.
Range indexes are very helpful for the situation involving a large operator. Let see an example to
understand how slicing is done with the help of the colon operator to form a new vector.
Example:
1. q<-c("shubham","arpita","nishka","gunjan","vaishali","sumit")
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
2. b<-q[2:5]
3. b
Output:
In R, the index vector can be out-of-order. Below is an example in which a vector slice with the
order of first and second values reversed.
Example:
1. q<-c("shubham","arpita","nishka","gunjan","vaishali","sumit")b<-q[2:5]
2. q[c(2,1,3,4,5,6)]
Output:
1. z=c("TensorFlow","PyTorch")
2. z
Output:-
Vector Arithmetic: -
1) Addition:-
Addition operator takes two vectors as operands, and returns the result of sum of two vectors.
a+b
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Example: -
In the following program, we create two integer vectors and add them using Addition Operator.
Example: -
a <- c(10, 20, 30, 40, 50)
b <- c(1, 3, 5, 7, 9)
result <- a + b
print(result)
Output: -
[1] 11 23 35 47 59
2) Subtraction:-
Subtraction operator takes two vectors as operands, and returns the result of difference of two
vectors.
a-b
Example:-
Output:-
[1] 9 17 25 33 41
3) Multiplication: -
Multiplication operator takes two vectors as operands, and returns the result of product of two
vectors.
a*b
Example: -
a <- c(10, 20, 30, 40, 50)
b <- c(1, 3, 5, 7, 9)
result <- a * b
Mr. P. M. More. (M.C.A.,M.Phil., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
print(result)
Output:-
[1] 10 60 150 280 450
4) Division:-
Division operator takes two vectors are operands, and returns the result of division of two
vectors.
a+b
Example: -
In the following program, we create two integer vectors and divide them using Division
Operator.
Example:-
a <- c(10, 20, 30, 40, 50)
b <- c(1, 3, 5, 7, 9)
result <- a / b
print(result)
Output:
[1] 10.000000 6.666667 6.000000 5.714286 5.555556