Operations on Vectors in R

Last Updated : 25 Jan, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Vectors are the most basic data types in R. Even a single object created is also stored in the form of a vector. Vectors are nothing but arrays as defined in other languages. Vectors contain a sequence of homogeneous types of data. If mixed values are given then it auto converts the data according to the precedence. There are various operations that can be performed on vectors in R. 
 

Creating a vector

Vectors can be created in many ways as shown in the following example. The most usual is the use of ‘c’ function to combine different elements together. 
 

Python3




# Use of 'c' function
# to combine the values as a vector.
# by default the type will be double
X <- c(1, 4, 5, 2, 6, 7)
print('using c function')
print(X)
  
# using the seq() function to generate
# a sequence of continuous values
# with different step-size and length.
# length.out defines the length of vector.
Y <- seq(1, 10, length.out = 5)
print('using seq() function')
print(Y)
  
# using ':' operator to create
# a vector of continuous values.
Z <- 5:10
print('using colon')
print(Y)


Output: 
 

using c function 1 4 5 2 6 7
using seq function 1.00  3.25  5.50  7.75 10.00
using colon 5  6  7  8  9 10

 

Accessing vector elements

Vector elements can be accessed in many ways. The most basic is using the ‘[]’, subscript operator. Following are the ways of accessing Vector elements:
 

Note: vectors in R are 1 based indexed, unlike the normal C, python, etc format where indexing starts from 0.

 

Python3




# Accessing elements using the position number.
X <- c(2, 5, 8, 1, 2)
print('using Subscript operator')
print(X[2])
  
# Accessing specific values by passing
# a vector inside another vector.
Y <- c(4, 5, 2, 1, 7)
print('using c function')
print(Y[c(4, 1)])
  
# Logical indexing
Z <- c(5, 2, 1, 4, 4, 3)
print('Logical indexing')
print(Z[Z>3])


Output: 
 

using Subscript operator 5
using c function 1 4
Logical indexing 5 4 4

 

Modifying a vector

Vectors can be modified using different indexing variations which are mentioned in the below code: 
 

Python3




# Creating a vector
X <- c(2, 5, 1, 7, 8, 2)
  
# modify a specific element
X[3] <- 11
print('Using subscript operator')
print(X)
  
# Modify using different logics.
X[X>9] <- 0
print('Logical indexing')
print(X)
  
# Modify by specifying the position or elements.
X <- X[c(5, 2, 1)]
print('using c function')
print(X)


Output: 
 

Using subscript operator 2  5 11  7  8  2
Logical indexing 2 5 0 7 8 2
using c function 8 5 2

 

Deleting a vector

Vectors can be deleted by reassigning them as NULL. To delete a vector we use the NULL operator. 
 

Python3




# Creating a vector
X <- c(5, 2, 1, 6)
  
# Deleting a vector
X <- NULL
print('Deleted vector')
print(X)


Deleted vector NULL

Arithmetic operations

We can perform arithmetic operations between 2 vectors. These operations are performed element-wise and hence the length of both the vectors should be the same. 
 

Python3




# Creating Vectors
X <- c(5, 2, 5, 1, 51, 2)
Y <- c(7, 9, 1, 5, 2, 1)
  
# Addition
Z <- X + Y
print('Addition')
print(Z)
  
# Subtraction
S <- X - Y
print('Subtraction')
print(S)
  
# Multiplication
M <- X * Y
print('Multiplication')
print(M)
  
# Division
D <- X / Y
print('Division')
print(D)


Output: 
 

Addition 12 11  6  6 53  3
Subtraction -2 -7  4 -4 49  1
Multiplication 35  18   5   5 102   2
Division 0.7142857  0.2222222  5.0000000  0.2000000 25.5000000  2.0000000

 

Sorting of Vectors

For sorting we use the sort() function which sorts the vector in ascending order by default. 
 

Python3




# Creating a Vector
X <- c(5, 2, 5, 1, 51, 2)
  
# Sort in ascending order
A <- sort(X)
print('sorting done in ascending order')
print(A)
  
# sort in descending order.
B <- sort(X, decreasing = TRUE)
print('sorting done in descending order')
print(B)


Output: 
 

sorting done in ascending order 1  2  2  5  5 51
sorting done in descending order 51  5  5  2  2  1

 



Similar Reads

List of Vectors in R
Vectors are a sequence of elements belonging to the same data type. A list in R, however, comprises of elements, vectors, variables or lists which may belong to different data types. In this article, we will study how to create a list consisting of vectors as elements and how to access, append and delete these vectors to lists. list() function in R
6 min read
Combine Vectors, Matrix or Data Frames by Columns in R Language - cbind() Function
cbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by columns. Syntax: cbind(x1, x2, ..., deparse.level = 1) Parameters: x1, x2: vector, matrix, data frames deparse.level: This value determines how the column names generated. The default value of deparse.level is 1. Example 1: # R program to illustrate # cbind
2 min read
Compute the beta value of Non-Negative Numeric Vectors in R Programming - beta() Function
beta() function in R Language is used to return the beta value computed using the beta function. The beta function is also known as Euler's integral of the first kind. Syntax: beta(a, b) Parameters: a, b: non-negative numeric vectors Example 1: # R program to illustrate # beta function # Calling the beta() function beta(1, 2) beta(2, 2) beta(3, 5)
1 min read
Get the natural logarithm of the beta value of Non-Negative numeric vectors in R Language - lbeta() Function
lbeta() function in R Language is used to return the natural logarithm of the beta function. The beta function is also known as Euler's integral of the first kind. Syntax: lbeta(a, b) Parameters: a, b: non-negative numeric vectors Example 1: # R program to illustrate # lbeta function # Calling the lbeta() function lbeta(1, 2) lbeta(2, 2) lbeta(3, 5
1 min read
Compute the Covariance between Two Vectors in R Programming - cov() Function
cov() function in R Language is used to measure the covariance between two vectors. Syntax: cov(x, y, method) Parameters: x, y: Data vectors method: Type of method to be used Example 1: # Data vectors x <- c(1, 3, 5, 10) y <- c(2, 4, 6, 20) # Print covariance using Pearson method print(cov(x, y, method = "pearson")) Output: [1] 30.6
1 min read
Compute the Correlation Coefficient Value between Two Vectors in R Programming - cor() Function
cor() function in R Language is used to measure the correlation coefficient value between two vectors. Syntax: cor(x, y, method) Parameters: x, y: Data vectors method: Type of method to be used Example 1: # Data vectors x <- c(1, 3, 5, 10) y <- c(2, 4, 6, 20) # Print covariance using Pearson method print(cor(x, y, method = "pearson"
1 min read
Creating a Data Frame from Vectors in R Programming
A vector can be defined as the sequence of data with the same datatype. In R, a vector can be created using c() function. R vectors are used to hold multiple data values of the same datatype and are similar to arrays in C language. Data frame is a 2 dimensional table structure which is used to hold the values. In the data frame, each column contain
5 min read
Generating sequenced Vectors in R Programming - sequence() Function
sequence() function in R Language is used to create a vector of sequenced elements. It creates vectors with specified length, and specified differences between elements. It is similar to seq() function. Syntax: sequence(x) Parameters: x: Maximum element of vector Example 1: # R program to create sequence of vectors # Calling sequence() function seq
1 min read
Generate Color Vectors of desired Length in R Programming - rainbow() Function
rainbow() function in R Language is a built in color palettes which can be used to quickly generate color vectors of desired length taken as the parameter and returns the hexadecimal code of the colours available. This hexadecimal code is of eight digits. This is because the last two digits specify the level of transparency (where FF is opaque and
1 min read
Compute the Parallel Minima and Maxima between Vectors in R Programming - pmin() and pmax() Functions
pmin() function in R Language is used to return the parallel minima of the input vectors. Syntax: pmin(x1, x2) Parameters: x1: vector one x2: vector two Example 1: # R program to illustrate # pmin() function # First example vector x1 <- c(2, 9, 5, 7, 1, 8) # Second example vector x2 <- c(0, 7, 2, 3, 9, 6) # Application of pmin() in R pmin(x1,
1 min read
Assigning Vectors in R Programming
Vectors are one of the most basic data structure in R. They contain data of same type. Vectors in R is equivalent to arrays in other programming languages. In R, array is a vector of one or more dimensions and every single object created is stored in the form of a vector. The members of a vector are termed as components . Assigning of Vectors There
5 min read
Types of Vectors in R Programming
Vectors in R programming are the same as the arrays in C language which are used to hold multiple data values of the same type. One major key point is that in R the indexing of the vector will start from ‘1’ and not from ‘0’. Vectors are the most basic data types in R. Even a single object created is also stored in the form of a vector. Vectors are
5 min read
Dot Product of Vectors in R Programming
In mathematics, the dot product or also known as the scalar product is an algebraic operation that takes two equal-length sequences of numbers and returns a single number. Let us given two vectors A and B, and we have to find the dot product of two vectors. Given that, [Tex]A = a_1i + a_2j + a_3k [/Tex] and, [Tex]B = b_1i + b_2j + b_3k [/Tex] where
3 min read
Cross Product of Vectors in R Programming
In mathematics, the cross product or also known as the vector product is a binary operation on two vectors in three-dimensional space and is denoted by the symbol 'X'. Given two linearly independent vectors a and b, the cross product, a Ă— b is a vector that is perpendicular to both a and b and thus normal to the plane containing them. Let we have g
4 min read
Convert an Excel column into a list of vectors in R
In this article, we will be discussing the different approaches to convert the Excel columns to vector in the R Programming language. File in use: Method 1: Using $-Operator with the column name In this method, we will be simply using the $-operator with the column name and the name of the data read from the excel file. Here, the name of the column
2 min read
How to Fix in R: $ operator is invalid for atomic vectors
In this article, we are going to see how to fix $ operator is invalid for atomic vectors in the R programming language. The error that one may face in R is: $ operator is invalid for atomic vectors Such an error is produced by the R compiler when we try to get an element of an atomic vector by using the $ operator. An atomic vector is simply a 1-di
4 min read
Getting and Setting Length of the Vectors in R Programming - length() Function: Title change need
In R, the length of a vector is the number of elements it contains. Vectors can be of different types, such as numeric, character, or logical, and the length() function is a versatile way to determine the number of elements in a vector. length() function in R Programming Language is used to get or set the length of a vector (list) or other objects.
4 min read
Append Operation on Vectors in R Programming
In this article, let us discuss different methods to concatenate/append values to a vector in R Programming Language. Append method in RVectors in the R Programming Language is a basic objects consisting of sequences of homogeneous elements. vector can be integer, logical, double, character, complex, or raw. Values can be appended/concatenated in a
3 min read
Combine Vectors, Matrix or Data Frames by Rows in R Language - rbind() Function
In this article, we will discuss how we Combine Vectors, Matrices, or Data Frames by Rows in R Programming Language using rbind function. What is rbind function?The rbind function combines or concatenates data frames or matrices by rows. the rbind stands for row binds it shows that it appends rows of one object to another. Syntax: rbind(x1, x2, ...
3 min read
R Vectors
R Vectors are the same as the arrays in R language which are used to hold multiple data values of the same type. One major key point is that in R Programming Language the indexing of the vector will start from '1' and not from '0'. We can create numeric vectors and character vectors as well.  Creating a vectorA vector is a basic data structure that
5 min read
Create Matrix from Vectors in R
In this article, we will discuss How to convert a vector to a matrix in R Programming Language. A vector is a basic object that consists of homogeneous elements. The data type of vector can be integer, double, character, logical, complex, or raw. A vector can be created by using the c() function. Syntax: x <- c(val1, val2, .....) To convert a ve
6 min read
Create a matrix from a list of vectors using R
In this article, we are going to learn how we can convert the list of vectors into a matrix using R Programming Language. If you want to convert simple vectors to a matrix not the list of vectors. The data type of vector can be integer, double, character, logical, complex, or raw. A vector can be created by using the c() function. To create a vecto
6 min read
Calculate the outer product of two vectors using R
In this article, we will explore different ways to Calculate the outer product of two vectors using R Programming Language. What is the outer product of two vectorsthe outer product of two vectors is a matrix where each element is the product of a corresponding element from the first vector with a corresponding element from the second vector. The r
3 min read
Subtracting similarly named elements in a list of vectors in R
When working with vectors in R, you might encounter a situation where you need to perform operations on elements with similar names across different vectors within a list. One common operation is subtraction. This article will guide you through the process of subtracting similarly named elements in a list of vectors in the R Programming Language. I
3 min read
Why Can't R's ifelse Statements Return Vectors?
In R, the ifelse() function is designed to perform element-wise conditional operations on vectors. However, a common point of confusion arises when trying to use ifelse() to return vectors (or lists) as elements in its output. The function's behavior and underlying design principles explain why ifelse() doesn't return vectors as expected in the R P
4 min read
How Can I Convert a List of Character Vectors to a Single Vector in R?
In R Language lists are a flexible data structure that can contain elements of different types, including vectors. When working with lists of character vectors, you might want to combine them into a single vector for easier manipulation or analysis. This can be done using various built-in functions like unlist() or using the purrr package for more
3 min read
Identical function in R with multiple vectors
When working with data in R, comparing different vectors to determine if they are exactly the same is a common task. The identical() function is a useful tool for this purpose. This article explores how to use identical() to compare multiple vectors in R and discuss their functionality. What is identical()?The identical() function in R tests whethe
4 min read
How to Draw Multiple CDF Plots of Vectors with Different Number of Rows in R
In statistical analysis, the Cumulative Distribution Function (CDF) is used to describe the probability that a random variable takes a value less than or equal to a given point. Visualizing CDFs is a powerful way to understand the distribution of data. In R, drawing multiple CDF plots for vectors with different numbers of rows can be achieved using
3 min read
DataFrame Operations in R
DataFrames are generic data objects of R which are used to store the tabular data. Data frames are considered to be the most popular data objects in R programming because it is more comfortable to analyze the data in the tabular form. Data frames can also be taught as mattresses where each column of a matrix can be of the different data types. Data
9 min read
Array Operations in R Programming
Arrays are the R data objects which store the data in more than two dimensions. Arrays are n-dimensional data structures. For example, if we create an array of dimensions (2, 3, 3) then it creates 3 rectangular matrices each with 2 rows and 3 columns. They are homogeneous data structures. Now, let’s see how to create arrays in R. To create an array
4 min read
Article Tags :
three90RightbarBannerImg