R Vectors

Last Updated : 20 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

R - VectorGeeksforgeeks

R – Vector

Creating a vector

A vector is a basic data structure that represents a one-dimensional array. to create a array we use the “c” function which the most common method use in R Programming Language.

R




# R program to create Vectors
 
# we can use the c function
# to combine the values as a vector.
# By default the type will be double
X<- c(61, 4, 21, 67, 89, 2)
cat('using c function', X, '\n')
 
# seq() function for creating
# a sequence of continuous values.
# length.out defines the length of vector.
Y<- seq(1, 10, length.out = 5)
cat('using seq() function', Y, '\n')
 
# use':' to create a vector
# of continuous values.
Z<- 2:7
cat('using colon', Z)


Output:

using c function 61 4 21 67 89 2  
using seq() function 1 3.25 5.5 7.75 10
using colon 2 3 4 5 6 7

Types of R vectors

Vectors are of different types which are used in R. Following are some of the types of vectors:

Numeric vectors

Numeric vectors are those which contain numeric values such as integer, float, etc. 

R




# R program to create numeric Vectors
 
# creation of vectors using c() function.
v1<- c(4, 5, 6, 7)
 
# display type of vector
typeof(v1)
 
# by using 'L' we can specify that we want integer values.
v2<- c(1L, 4L, 2L, 5L)
 
# display type of vector
typeof(v2)


Output:

[1] "double"
[1] "integer"

Character vectors

Character vectors in R contain alphanumeric values and special characters. 

R




# R program to create Character Vectors
 
# by default numeric values
# are converted into characters
v1<- c('geeks', '2', 'hello', 57)
 
# Displaying type of vector
typeof(v1)


Output:

[1] "character"

Logical vectors

Logical vectors in R contain Boolean values such as TRUE, FALSE and NA for Null values. 

R




# R program to create Logical Vectors
 
# Creating logical vector
# using c() function
v1<- c(TRUE, FALSE, TRUE, NA)
 
# Displaying type of vector
typeof(v1)


Output:

[1] "logical"

Length of R vector

In R, the length of a vector is determined by the number of elements it contains. we can use the length() function to retrieve the length of a vector.

R




# Create a numeric vector
x <- c(1, 2, 3, 4, 5)
 
# Find the length of the vector
length(x)
# Create a character vector
y <- c("apple", "banana", "cherry")
 
# Find the length of the vector
length(y)
# Create a logical vector
z <- c(TRUE, FALSE, TRUE, TRUE)
 
# Find the length of the vector
length(z)


Output:

> length(x)
[1] 5

> length(y)
[1] 3

> length(z)
[1] 4

Accessing R vector elements

Accessing elements in a vector is the process of performing operation on an individual element of a vector. There are many ways through which we can access the elements of the vector. The most common is using the ‘[]’, symbol.

Note: Vectors in R are 1 based indexing unlike the normal C, python, etc format.

R




# R program to access elements of a Vector
 
# accessing elements with an index number.
X<- c(2, 5, 18, 1, 12)
cat('Using Subscript operator', X[2], '\n')
 
# by passing a range of values
# inside the vector index.
Y<- c(4, 8, 2, 1, 17)
cat('Using combine() function', Y[c(4, 1)], '\n')


Output:

Using Subscript operator 5 
Using combine() function 1 4

Modifying a R vector

Modification of a Vector is the process of applying some operation on an individual element of a vector to change its value in the vector. There are different ways through which we can modify a vector: 

R




# R program to modify elements of a Vector
 
# Creating a vector
X<- c(2, 7, 9, 7, 8, 2)
 
# modify a specific element
X[3] <- 1
X[2] <-9
cat('subscript operator', X, '\n')
 
# Modify using different logics.
X[1:5]<- 0
cat('Logical indexing', X, '\n')
 
# Modify by specifying
# the position or elements.
X<- X[c(3, 2, 1)]
cat('combine() function', X)


Output:

subscript operator 2 9 1 7 8 2 
Logical indexing 0 0 0 0 0 2
combine() function 0 0 0

Deleting a R vector

Deletion of a Vector is the process of deleting all of the elements of the vector. This can be done by assigning it to a NULL value. 

R




# R program to delete a Vector
 
# Creating a Vector
M<- c(8, 10, 2, 5)
 
# set NULL to the vector
M<- NULL
cat('Output vector', M)


Output:

Output vector NULL

Sorting elements of a R Vector

sort() function is used with the help of which we can sort the values in ascending or descending order. 

R




# R program to sort elements of a Vector
 
# Creation of Vector
X<- c(8, 2, 7, 1, 11, 2)
 
# Sort in ascending order
A<- sort(X)
cat('ascending order', A, '\n')
 
# sort in descending order
# by setting decreasing as TRUE
B<- sort(X, decreasing = TRUE)
cat('descending order', B)


Output:

ascending order 1  2  2  7  8 11
descending order 11 8 7 2 2 1


Previous Article
Next Article

Similar Reads

Operations on Vectors in R
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 tha
4 min read
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
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
R Tutorial | Learn R Programming Language
R Programming Tutorial is designed for beginners and experts. This free R Tutorial gives you knowledge basic to advanced of concepts of the R programming language. Here you will get a detailed introduction, features, installation, variables, data types, operators, if statements, vectors, data handling, graphics, and statistical modeling of R progra
9 min read
R Programming Language - Introduction
The R Language stands out as a powerful tool in the modern era of statistical computing and data analysis. Widely embraced by statisticians, data scientists, and researchers, the R Language offers an extensive suite of packages and libraries tailored for data manipulation, statistical modeling, and visualization. In this article, we explore the fea
7 min read
Article Tags :