Vectors in R programming is one of the most used or useful function. Vectors are considered as the basic data objects in the R language. If you don’t know, there are 6 types of Vectors are there –

  • Logical vectors
  • Integer Vector
  • Double vector
  • Character vector
  • Complex vector
  • Raw vector
vector in r

What is a Vector in R programming?

A vector is an R language data object which contains a sequence of elements of the same data type. The elements in the vector are called as components.

df<-c(1,2,3,4,5)

The above is the basic example of the Vector in R programming. It has 5 elements in it i.e. 1,2,3,4 and 5.

Types of Vectors in R

vector in r programming

As I mentioned earlier, there are 6 types of vectors are there in the R language. Let’s see each one of them with an example to get a good hold of those.

1. Vector with type Logical:

print(FALSE)
FALSE

2.Vector with Type Character:

print("chi")
chi

3.Vector with type Double:

print(25.5)
25.5

4.Vector with type Integer:

print(25M)
25

5.Vector with type Complex:

print(2+2i)
2+2i

6.Vector with type Raw:

print(chartoRaw('Hey'))
68 65 79

Create Multi-Elemental vector in R

Yes, as the title suggest, you can easily create a vector which has multiple elements in it.

Let’s see how it works.

 df<-c(1:20)
df
1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 

Let’s see another example – If the ending / final element does not match with the regular sequence then it can be neglected.

df<-1.5:5.9
df
1.5 2.5 3.5 4.5 5.5

The above output shows that the given number (final value) is not matching the sequence and hence it is neglected.

Access elements in a vector

In this section, let’s see how we can access the elements present in the vector.

df<-c(13:23)
df

x<-df[c(2,4,6,8)]
x
14 16 18 20

In the above vector, we have accessed the positions of 2,4,6 and 8. The function returned those values which we have requested to print.

Adding the vectors:

You can add the two vectors using the arithmetic operator of sum.

#creating vector 
vector_1 <-c(1,2,3,4)
vector_2 <-c(6,7,8,9)
#Adds the vectors 
vector_1+vector_2
7  9 11 13

Just like the above, you can create vectors, manipulate them and print them as well.

Wrapping Up – Vectors in R programming

Well, vectors are the R data objects which store the data in sequence and of the same data type.

There are 6 vector types and each of them is emplaned in the above sections with a reference of each individually.

I hope by now you will get a better idea about the vectors in R programming. That’s all for now. Happy Vectors!!!

More read: R documentation

Categorized in:

Tagged in: