8 R Vector Operations with Examples – A Complete Guide for R Programmers
If you are struggling with the R vector concept, then you have landed on the right page. This article is specially designed to help you to create and access R vectors. Here you will learn to perform many operations on them and will discover important applications of R vectors.
R vector is the basic data structure, which plays an essential role in R programming. So, let’s start with our tutorial.
Keeping you updated with latest technology trends, Join DataFlair on Telegram
What is R Vector?
A vector is a sequence of elements that share the same data type. These elements are known as components of a vector.
R vector comes in two parts: Atomic vectors and Lists. They have three common properties:
- Type function – What it is?
- Length function – How many elements it contains.
- Attribute function – Extra arbitrary metadata.
These data structures share one difference, that is, they differ in the type of their elements: All elements of an atomic vector must be of the same type, whereas the elements of a list can have different types.
We have discussed R Lists in detail in our previous tutorial, you must check it.
Atomic Vectors in R
There are four common types of R atomic vectors:
1. Numeric Data Type
Decimal values are referred to as numeric data types in R. If we assign a decimal value for any variable g, as given below then, g will become a numeric type.
> #Author DataFlair > g <- 53.5 #Assigning a decimal value to g > g #Printing the value of g
Adding the class:
> class(g) #Printing the class name of g
2. Integer Data Type
A numeric value with no fraction called integer data is represented by “Int”. -54 and 23 are two of the examples of an integer. Int size is 2 bytes while long Int size is 4 byte.
In order to assign an integer to a variable, there are two ways:
- The first way is to use the as.integer() function:
> a <- as.integer(4) #Using as.integer() > a #printing a
For checking data type:
> typeof(a) #checking data-type of a
- The second way is the appending of L to the value:
> b <- 4L #Appending L to 4 > b #printing b
For checking data type:
> typeof(b) #Checking data-type of b
3. Character Data Type
The character is held as the one-byte integer in memory. There are two ways to create a character data type value in R:
- The first method is by typing a string between ” “
> x = "DataFlair" > x
For determining the type of x:
- In order to convert a number into character, make use of as.character() function as follows:
> y = as.character(42) > y
For determining the type of y:
4. Logical Data Type
A logical data type returns either of the two values – TRUE or FALSE based on which condition is satisfied.
a =3; b =6 #sample values g = a>b # is a larger than b? g #print the logical value
Learn about the R Data Types in detail
How to Create Vector in R?
The c() function is used for creating a vector in R. This function returns a one-dimensional array, also known as vector.
> x <- c(1,2,3,4) > x
Ways to Create Vectors in R
There are several other ways of creating a vector:
1. Using the Operator
> x <- 1:5 > x
For y operator:
> y <- 5:-5 > y
2. Create R vector using seq() function
There are also two ways in this. The first way is to set the step size and the second method is by setting the length of the vector.
- Setting step size with ‘by’ parameter:
> seq(2,4, by = 0.4)
- Specifying length of vector with the ‘length.out’ feature:
> seq(1,4, length.out = 5)
Must Learn – How to apply Functions over R Vectors
How to Access Elements of R Vectors?
With the help of vector indexing, we can access the elements of vectors. Indexing denotes the position where the values in a vector are stored. This indexing can be performed with the help of integer, character or logic.
1. Indexing with Integer Vector
Unlike many programming languages like Python, C++, Java etc. where the indexing starts from 0, the indexing of vectors in R starts with 1.
We can perform indexing by specifying integer value in square braces [ ] next to our vector.
> x #indexing with vector
2. Indexing with Character Vector
Character vector indexing can be done as follows:
> x <- c("One" = 1, "Two" = 2, "Three" = 3) > x["Two"]
3. Indexing with Logic Vector
In logical indexing, the positions whose corresponding position has logical vector TRUE are returned. For example, in the below code, R returns the positions of 1 and 3, where the corresponding logical vectors are TRUE.
> a <- c(1,2,3,4) > a[c(TRUE, FALSE, TRUE, FALSE)]
Operations in R Vector
1. Combining Vector in R
Functions are used to combine vectors. In order to combine the two vectors in R, we will create two new vectors ‘n’ and ‘s’. Then, we will create another vector that will combine these two using c(n,s) as follows:
> #Author DataFlair > n = c(1, 2, 3, 4) > s = c("Hadoop", "Spark", "HIVE", "Flink") > c(n,s)
Wait! Have you checked – Data Structures in R
2. Arithmetic Operations on Vectors in R
Arithmetic operations on vectors can be performed member-by-member.
Suppose we have two vectors a and b:
> #Author DataFlair > a = c (1, 3) > b = c (1, 3) > a + b #Addition
> a - b #Subtraction
> a / b #Division
For remainder operation:
> a %% b #Remainder Operation
3. Logical Index Vector in R
By using a logical index vector in R, we can form a new vector from a given vector, which has the same length as the original vector. If the corresponding members of the original vector are included in the slice, then vector members are TRUE and otherwise FALSE.
> #Author DataFlair > S = c("bb", "cc") > L = c(TRUE, TRUE) #Defining our Logical Vector > S[L] #This will return elements of vector S that corrospond to logic vector L
4. Numeric Index
For indexing a numerical value in R, we specify the index between square braces [ ]. If our index is negative, then R will return us all the values except for the index that we have specified. For example, specifying [-2] will prompt R to convert -2 into its absolute value and then search for the value that occupies that index.
> # Author DataFlair > x <- c("aa", "bb", "cc", "dd", "ee") #Creating our vector > x
For negative index:
> x[-2] #Using Negative Index
For out of range index:
> x #Using an out-of-range index
You must definitely explore the Numeric and Character Functions in R
5. Duplicate Index
The index vector allows duplicate values. Hence, the following retrieves a member twice in one operation.
> # Author DataFlair > s = c("aa", "bb", "cc", "dd", "ee") > s[c(2,3,3)]
6. Range Indexes
To produce a vector slice between two indexes, we can use the colon operator “:“. It is convenient for situations involving large vectors.
> # Author DataFlair > s = c("aa", "bb", "cc", "dd", "ee") > s[1:3]
7. Out-of-order Indexes
The index vector can even be out-of-order. Here is a vector slice with the order of first and second members reversed.
> s [ c (2, 1, 3) ]
8. Named Vectors Members
We first create our vector of characters:
> v = c("Hadoop", "Spark") > v
Then, we name the first vector member as “First” and the second member as “Second”.
> names(v) = c("First", "Second") > v
We retrieve the first member by its name as follows:
We can also reverse the order using the character string index vector:
> v[c("Second", "First")]
Applications of R Vectors
- Vectors are used in machine learning for principal component analysis. They are extended to eigenvalues and eigenvector which are then used for performing decomposition in vector spaces.
- The input that is provided to the deep learning model is in the form of vectors. This vector consists of standardized data that is supplied to the input layer of the neural network.
- Vectors are also highly useful in developing support vector machine algorithms.
- Furthermore, vector operations are utilized in neural networks in the hidden layer for various operations like image recognition and text processing.
We have studied the R vector in detail. Also, we have mentioned the different type of vectors and how to use it. So, this above information will surely help the person who is not so much aware of vectors and their uses. R is a beautiful language. The more you learn R, the more you start liking it.
Now that you are a master of R Vectors, get ready for R Matrix Operations and Applications
Still, you have any query in R vector, please comment in the section given below. We will be glad to solve your doubts.