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,

R vector Tutorial

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.

For Example-

> #Author DataFlair
> g <- 53.5 #Assigning a decimal value to g
> g #Printing the value of g

Output-

[1] 53.5

> class(g) #Printing the class name of g

Output-

[1] “numeric”

R numeric Data Types Example

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

Output- 

[1] 4

> typeof(a) #checking data-type of a

Output- 

[1] “integer”

  • The second way is the appending of L to the value –
> b <- 4L #Appending L to 4 
> b #printing b

Output- 

[1] 4

> typeof(b) #Checking data-type of b

Output- 

[1] “integer”

R integer Data Types Example

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

Output- 

[1] “DataFlair”

> typeof(x)

Output- 

[1] “character”

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

Output- 

[1] “42”

> typeof(y)

Output- 

[1] “character”

R Character Data Type with Example

 

2.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- FALSE

R Logical Data Type with Example

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.

For example-

> x <- c(1,2,3,4)
> x

Output-

[1] 1 2 3 4

How to create vector in R

Do you knowHow 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] 1 2 3 4 5

> y <- 5:-5
> y

Output-

[1] 5 4 3 2 1 0 -1 -2 -3 -4 -5

Create R vector using the operator 

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-

[1] 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] 1.00 1.75 2.50 3.25 4.00

Create R vector using seq() function It’s the right time to know about Vector Functions used in R

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.

> x

Output-

[1] 1 2 3 4 5

> x[2] #indexing with vector

Output-

[1] 2

 Indexing with Integer 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"]

Output-

Two

2

 Indexing with Character Vector

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] 1 3

R logic Index with Example

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 –

For Example-

> #Author DataFlair
> n = c(1, 2, 3, 4) 
> s = c("Hadoop", "Spark", "HIVE", "Flink")
> c(n,s)

Output-

[1] “1” “2” “3” “4” “Hadoop” “Spark” “HIVE” “Flink”

Combine vector in R with Example

5.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

Output-

[1] 2 6

> a - b #Subtraction

Output-

[1] 0 0

> a / b #Division

Output-

[1] 1 1

> a %% b #Remainder Operation

Output-

[1] 0 0

R Arithmetic operations with Example

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.

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-

[1] “bb” “cc”

R Logical Index Vector in R with Example

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.

For Example-

> # Author DataFlair
> x <- c("aa", "bb", "cc", "dd", "ee") #Creating our vector
> x[3]

Output-

[1] “cc”

> x[-2] #Using Negative Index

Output-

[1] “aa” “cc” “dd” “ee”

> x[15] #Using an out-of-range index

Output-

[1] NA

Numeric Index in R

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.

For Example-

> # Author DataFlair
> s = c("aa", "bb", "cc", "dd", "ee")
> s[c(2,3,3)]

Output-

[1] “bb” “cc” “cc”

R duplicate Index with Example

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.

For Example- 

> # Author DataFlair
> s = c("aa", "bb", "cc", "dd", "ee")
> s[1:3]

Output-

[1] “aa” “bb” “cc”

R Range Index with Example

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.

For Example- 

> s [ c (2, 1, 3) ]

Output-

[1] “bb” “aa” “cc”

Out-of-order Indexes in R With Example

5.8  Named Vectors Members 

We first create our vector of characters –

> v = c("Hadoop", "Spark")
> v

Output-

[1] “Hadoop” “Spark”

We then name the first vector member as “First” and second member as “Second”

> names(v) = c("First", "Second")
> v

Output-

First Second

“Hadoop” “Spark”

We retrieve the first member by its name as follows:

> v["First"]

Output-

First
“Hadoop”

We can also reverse the order using the character string index vector –

> v[c("Second", "First")]

Output-

Second First
“Spark” “Hadoop”

R Named Vectors Members  with Example

So, this was all on R vector tutorial. Hope you like the R language vector tutorial.

R Quiz

6. 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 decompositions in vector spaces.
  2. 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.
  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.

7. Conclusion

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.

3 Responses

    • DataFlair Team says:

      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.

  1. Sandhya says:

    How vectors used in reality in r programming can u explain it

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.