R Vector – How to Create, Combine and Index Vectors in R?

In this TechVidvan tutorial, you’ll learn about vector in R programming. You’ll learn to create, combine, and index vectors in R.

Vectors are the simplest data structures in R. They are sequences of elements of the same basic type.

These types can be numeric, integer, complex, character, and logical. In R, the more complicated data structures are made with vectors as building-blocks.

In this article, you will get the answer to all these questions in detail:

So without further ado, let’s begin!

How to create vector in R?

There are numerous ways to create an R vector:

1. Using c() Function

To create a vector, we use the c() function:

Code:

> vec <- c(1,2,3,4,5) #creates a vector named vec
> vec #prints the vector vec

Output:
vectors - create vector using c()

Follow TechVidvan on Google & Stay updated with latest technology trends

2. Using assign() function

Another way to create a vector is the assign() function.

Code:

> assign("vec2",c(6,7,8,9,10)) #creates a vector named vec2
> vec2                         #prints the vector vec2

 

Output:

create R vector using assign() function

3. Using : operator

An easy way to make integer vectors is to use the : operator.

Code:

> vec3 <- 1:20
> vec3

Output:

create R vectors using : operator

What are the types of vectors in R?

A vector can be of different types depending on the elements it contains. These may be:

1. Numeric Vectors

Vectors containing numeric values.

Code:

> num_vec <- c(1,2,3,4,5)
> num_vec

2. Integer Vectors

Vectors containing integer values.

Code:

> int_vec <- c(6L,7L,8L,9L,10L)
> int_vec

3. Logical Vectors

Vectors containing logical values of TRUE or FALSE.

Code:

> log_vec <- c(TRUE,FALSE,TRUE,FALSE,FALSE)
> log_vec

4. Character Vectors

Vectors containing text.

Code:

> char_vec <- c("aa","bb","cc","dd","ee")
> char_vec

5. Complex Vectors

Vectors containing complex values.

Code:

> comp_vec <- c(12+1i,3i,5+4i,4+9i,6i)
> comp_vec

Output:

R vectors types of vectors

How to find the type of R vector?

We can use the typeof() function to find the type of a vector. For example:

Code:

> typeof(num_vec)
> typeof(int_vec)
> typeof(log_vec)
> typeof(char_vec)
> typeof(comp_vec)

Output:

R-vectors-typeof()-function

Note: The typeof() function returns “double” for numeric values. This is because of the way numeric-class stores a value. The numeric class stores values as double-precision floating-point numbers. Their type is double while their class is numeric.

How to combine R vectors?

The c() function can also combine two or more vectors and add elements to vectors.

Example 1

Code:

> vec4 <- c(vec, vec2)
> vec4

Example 2

Code:

> vec5 <- c(vec4,4,55,vec)
> vec5

Output:

combining R vectors

What is coercion in R vector?

Vectors only hold elements of the same data type. If there is more than one data type, the c() function converts the elements. This is known as coercion. The conversion takes place from lower to higher types.

logical < integer < double < complex < character.

Code:

> vec6 <- c(1,FALSE,3L,12+5i,"hello")
> typeof(vec6)

Output:

coercion in R vector

How to access elements of R vector?

We use vector indexing to access the elements of a vector. We can select or omit elements of a vector, by appending an index vector in square brackets to the name of the vector.

There are four types of index vectors:

  1. Logical index vector
  2. Positive-integral index vector
  3. Negative-integral index vector
  4. Character index vector

Let us look at these different indexing techniques:

1. Logical index vectors

We can use a vector of logical values to index another vector of the same length. R includes the elements corresponding to TRUE in the index vector and omits the elements corresponding to FALSE. For example:

Code:

> logind_vec <- vec[c(FALSE,TRUE,FALSE,TRUE,TRUE)]
> logind_vec

Output:

R vectors logical indexing

Instead of using logical vectors of equal length, we can also use a logical condition. This includes the elements which satisfy the condition while removes those who don’t.

Code:

> logind_vec2 <- vec3[(vec3%%3)==0] #only allow those divisible by 3
> logind_vec2

Output :

vectors logical indexing

2. Positive-integral index vectors

Vector indices in R start from 1. We can use positive integers to select specific elements. We can also use vectors of positive integers to include multiple specific elements while leaving others.

Example 1

Code:

> posint_vec <- vec[3]
> posint_vec

Example 2

Code:

> posint_vec2 <- vec4[c(2,3,6,7,9)]
> posint_vec2

Output:

R vectors positive integral indexing

3. Negative-integral index vectors

In negative integral indexing, negative integers denote the elements to be excluded. When using negative integral vectors, R removes the denoted elements and returns the remaining as the result.

Code:

> negint_vec <- vec[c(-2,-4)]
> negint_vec

Output:

negative integral indexing in R vectors

4. Character indexing vectors

We use a character vector, only to index vectors with a ‘names’ attribute. Character vector indexing is useful when dealing with named R vectors.

Code:

> named_vec <- c("first"=1,"second"=2,"third"=3,"fourth"=4)
> named_vec
> charind_vec <- named_vec[c("first","second","fourth")] 
> charind_vec

Output:

character index in R vectors

What are some basic vector arithmetic in R?

R performs arithmetic operations on vectors memberwise. This means that the operations are performed on each member. For example:

Multiplication:

> multivec <- vec*2
> multivec

Addition:

> vec_plus_three <- vec+3
> vec_plus_three

Subtraction:

> vec_min_one <- vec-1
> vec_min_one

Output:

R vector arithmetic multivec

We can also perform an arithmetic operation like an addition of two vectors of equal length. This adds the corresponding members in the two vectors. For example:

Addition of vectors

> vector_add <- vec+vec2 #vec = 1,2,3,4,5 vec2 = 6,7,8,9,10
> vector_add

Multiplication of vector

> vector_mul <- vec*vec2
> vector_mul

Subtraction of vector

> vector_sub <- vec2-vec
> vector_sub

Division of vector

> vector_div <- multivec/vec # multivec = 2,4,6,8,10
> vector_div

Output:

R vectors arithmetic add,sub,mul,div

If the two vectors are of unequal length, the shorter one will be recycled to match the longer vector.

Code:

> recycle_vec <- vec*vec4
> recycle_vec

Output:

arithmetic recycling in R vector

Note: Here, the first vector vec has five elements. The second vector vec4 has ten elements. Therefore, the first vector is cycled twice to match the second.

What is vector function in R?

R has many functions that can manipulate vectors or get more information about them. Here are some of the commonly used functions:

1. seq() seq() function generates regular numeric sequences. The function has the following arguments:

  • from: starting value
  • to: ending value
  • by: increment (default is 1)
  • length.out: length of the sequence
  • along.with: the length of this argument can define the length of the sequence.

Code:

> vec_seq <- seq(from=1,to=20,length=30)
> vec_seq

2. rep() – The rep() function repeats a given numeric vector. The function has the following arguments:

  • X: x is the numeric vector that is repeated.
  • times: number of repetitions.
  • each: number of repetitions for each element of the vector.
  • length.out: the length of the resultant vector. The function repeats until it reaches the length.

Code:

> vec_rep <- rep(c(2,3,4), times=3)
> vec_rep

3. sum() – The sum() function returns an integer value which is the sum of all the elements in a vector.

Code:

> sum(vec_rep)

4. Type checking and conversion functions – the functions as.numeric() / as.character() / as.logical() / as.integer() can convert a vector into their corresponding type. The functions is.numeric() /is.character() /is.logical() etc. tell whether the vector is of the corresponding type or not.

Code:

> is.numeric(vec_rep)
> as.character(vec_rep)

vector functions in R

Summary

Vectors are one of the basic data structures of R. They are sequences of values of the same data type. We can classify them as one-dimensional, homogeneous data structures.

Don’t know much about inbuilt data structures in R? Then have a look at basic data structures in R with examples.

In this tutorial, we learned about R vectors. We learned how to create vectors and how many types of vectors there are. We also looked at coercion and the various indexing techniques for vectors.

Finally, we explored the mechanics of vector arithmetic in R and a few functions that can generate and manipulate vectors.

If you like our content, then please give your feedback in the comment section.

Keep learning!!

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google | Facebook


3 Responses

  1. Donghyeon Gahng says:

    Thank you very much for the great resource for beginners. What you wrote really very well sums up the basics in a very clear and synthetic way.

  2. Unnikishnan says:

    Marvelous teaching of R.

  3. Brian says:

    Brilliant. Your work has more Clarity and understanding.
    In fact I have made a step in my R language.

Leave a Reply

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