8 R Vector Operations with Examples – A Complete Guide for R Programmers
Job-ready Online Courses: Knowledge Awaits – Click to Access!
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.
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.
For example:
> #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
Output:
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
Output:
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:
> typeof(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:
> typeof(y)
Output:
4. Logical Data Type
A logical data type returns either of the two values – TRUE or FALSE based on which condition is satisfied.
For example:
a =3; b =6 #sample values g = a>b # is a larger than b? g #print the logical value
Output:
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.
For example:
> x <- c(1,2,3,4) > x
Output:
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
Output:
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)
Output:
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.
> x
We can perform indexing by specifying integer value in square braces [ ] next to our vector.
> x[2] #indexing with vector
Output:
2. Indexing with Character Vector
Character vector indexing can be done as follows:
> x <- c("One" = 1, "Two" = 2, "Three" = 3) > x["Two"]
Output:
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:
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:
For example:
> #Author DataFlair > n = c(1, 2, 3, 4) > s = c("Hadoop", "Spark", "HIVE", "Flink") > c(n,s)
Output:
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.
For example:
Suppose we have two vectors a and b:
> #Author DataFlair > a = c (1, 3) > b = c (1, 3) > a + b #Addition
For subtraction:
> a - b #Subtraction
For division:
> a / b #Division
For remainder operation:
> a %% b #Remainder Operation
Output:
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.
For example:
> #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:
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.
For example:
> # Author DataFlair > x <- c("aa", "bb", "cc", "dd", "ee") #Creating our vector > x[3]
For negative index:
> x[-2] #Using Negative Index
For out of range index:
> x[15] #Using an out-of-range index
Output:
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.
For example:
> # Author DataFlair > s = c("aa", "bb", "cc", "dd", "ee") > s[c(2,3,3)]
Output:
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.
For example:
> # Author DataFlair > s = c("aa", "bb", "cc", "dd", "ee") > s[1:3]
Output:
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.
For example:
> s [ c (2, 1, 3) ]
Output:
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:
> v["First"]
We can also reverse the order using the character string index vector:
> v[c("Second", "First")]
Output:
Advanced Vector Operations
Beyond the fundamental operations outlined earlier, R offers advanced functionalities for manipulating vectors. These include functions for sorting vectors, finding unique elements, and reshaping data structures.
Sorting vectors can be achieved using functions like sort() and order(), allowing for ascending or descending arrangements based on elements’ values. Moreover, finding unique elements within a vector can be done with unique(), which returns a vector with only the unique elements present in the original vector.
Additionally, R provides functions like reshape() and rbind() for reshaping vectors into different dimensions or combining multiple vectors into matrices or data frames.
Advantages of Vectors
One of the key advantages of R vectors is their support for vectorized operations, which enable efficient computation on large datasets. Vectorization allows R to perform operations on entire vectors at once, rather than iterating through each element individually. This not only simplifies code but also significantly improves performance, especially when dealing with extensive datasets. By leveraging vectorized operations, R programmers can write concise and expressive code that executes efficiently, making it an ideal choice for data manipulation and analysis tasks.
Applications of R Vectors
1. 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.
2. 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.
3. Vectors are also highly useful in developing support vector machine algorithms.
4. Furthermore, vector operations are utilized in neural networks in the hidden layer for various operations like image recognition and text processing.
Summary
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.
We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google
super
Thanks Nathiya for taking time and leaving a valuable feedback for us. We recommend you to learn more topics in R, surely you will love them.
Best wishes to you.
How vectors used in reality in r programming can u explain it
Hey Sandhya,
Vectors, by their definition store data. These vectors have applications in machine learning implementations.
how to find the count of the number of elemnts present in a vector?
Hi Mopidevi,
You can use length(vector) function to count the number of elements present in the R vector.
Hope, it helps!
Awesome content
I can do a lot of hands-on now!!!
Amazing Stuff.Highly organized and rich.