8 R Vector Operations With Example – A Complete Guide for Beginners
If you are struggling with R vectors, 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.
A vector is a sequence of elements that share the same data type. R vector is the basic data structure, which plays an important role in R programming,
1. 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.
A vector is the basic form of data structure in R. 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 the same type, whereas the elements of a list can have different types. We have discussed R Lists in our previous blog, Here we are going to discuss only Atomic Vectors.
2. Atomic Vectors in R
There are four common types of R Atomic Vectors:
2.1 Numeric Data Type
Decimal values referred to as numeric data types in R. If we assign a decimal value for any variable g like given below, g will become a numeric type.
> #Author DataFlair > g <- 53.5 #Assigning a decimal value to g > g #Printing the value of g
> class(g) #Printing the class name of g
2.2 Integer Data Type
A numeric value with no fraction called integer data, represented by “Int”. -54 and 23 are two of the examples of integer. Int size is 2 bytes while long Int size is 4 byte.
Want to make a career in R? – Get the latest Career Opportunities in R
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
> 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
> typeof(b) #Checking data-type of b
2.3 Character Data Type
The char held as the one-byte integer in memory and it also held as a 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
Get a Free guide to master the R Data Types
- In order to convert a number into character, we make use of as.character() function as follows:
> y = as.character(42) > y
2.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
3. 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
Output- 1 2 3 4
Do you know – How to create and work with Arrays in R?
3.1 Ways to create vectors in R
There are several other ways of creating a vector –
3.1.1 Create R vector using the operator
> x <- 1:5 > x
Output- 1 2 3 4 5
> y <- 5:-5 > y
Output- 5 4 3 2 1 0 -1 -2 -3 -4 -5
3.1.2 Create R vector using seq() function
There are also two ways in this. 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)
Output- 2.0 2.4 2.8 3.2 3.6 4.0
- Specifying length of vector with the ‘length.out’ feature –
> seq(1,4, length.out = 5)
Output- 1.00 1.75 2.50 3.25 4.00
4. 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.
4.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.
Output- 1 2 3 4 5
> x #indexing with vector
4.2 Indexing with Character Vector
Character vector indexing can be done as follows –
> x <- c("One" = 1, "Two" = 2, "Three" = 3) > x["Two"]
4.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)]
Output- 1 3
Before we start the next topic, you should have an excellent command on R matrix Operations
5. Operations in R Vector
5.1 Combining Vector in R
Functions are used to combine vectors. In order to combine the two vectors in R, we will create two 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)
Output- “1” “2” “3” “4” “Hadoop” “Spark” “HIVE” “Flink”
5.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
Output- 2 6
> a - b #Subtraction
Output- 0 0
> a / b #Division
Output- 1 1
> a %% b #Remainder Operation
Output- 0 0
Recommended Reading – Factor Functioning in R
5.3 Logical Index Vector in R
By using a logical index vector in Rwe 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 include 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
Output- “bb” “cc”
5.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
> x[-2] #Using Negative Index
Output- “aa” “cc” “dd” “ee”
> x #Using an out-of-range index
Let’s enhance our skills by learning Arguments in R
5.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)]
Output- “bb” “cc” “cc”
5.6 Range Indexes
To produce a vector slice between two indexes, we can use the colon operator “:“. This is convenient for situations involving large vectors.
> # Author DataFlair > s = c("aa", "bb", "cc", "dd", "ee") > s[1:3]
Output- “aa” “bb” “cc”
5.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) ]
Output- “bb” “aa” “cc”
5.8 Named Vectors Members
We first create our vector of characters –
> v = c("Hadoop", "Spark") > v
Output- “Hadoop” “Spark”
We then name the first vector member as “First” and 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")]
So, this was all on R vector tutorial. Hope you like the R language vector tutorial.
6. 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 decompositions in vector spaces.
- The input that is provided to the deep learning model is in the form of vectors. This vector is 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.
Hence, 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, let us get ready for Control Structures in R.
Still, you have any query in R vector, please comment in the section given below. We will be glad to solve your doubts.