## R Vectors

Vectors are the basic R data objects. There are six basic (‘atomic’) vector types: logical, integer, real, complex, string (or character) and raw.

We can create vectors using c() function, seq() function or using colon(): operator.

length() is the property of vector to check number of elements in a vector.

typeof() is the property of vector to check type of vector.

**Example1: Create Vector using Colon : operator**

> x

[1] 2 3 4 5 6 7 8 9 10 11

> y<-21:33
> y

[1] 21 22 23 24 25 26 27 28 29 30 31 32 33

> z<-10:-1
> z

[1] 10 9 8 7 6 5 4 3 2 1 0 -1

**Example2: Using seq() function.**

seq() function generates regular sequences.

> vect1<-seq(1, 10, by = 2)
> vect1

[1] 1 3 5 7 9

> vect2<-seq(1,20,by=4)
> vect2

[1] 1 5 9 13 17

> vect3<-seq(1,8,0.5)
> vect3

[1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0

**Example2: Using c() function.**

c() function is used to convert logical and numeric values to characters.

> vect4<-c("pytho","r",9,FALSE)
> vect4

[1] “pytho” “r” “9” “FALSE”

**Access Vector Elements:**

Vector elements can be accessed using Indexes. As discussed above, we get the length of vector using length property of vector.

Index values are ranged between 1 and length of vector.

We can also use negative indexes to return all elements except that those specified.But, we cannot mix positive and negative integers while indexing and real numbers, if used, are truncated to integers.

> x<-c("January","February","March","April","May","June","July","August")
> x

[1] “January” “February” “March” “April” “May” “June” “July” “August”

> x[1]

[1] “January” –>First element

> x[4] –> 4th element

[1] “April”

> length(x) –>Length of Vector

[1] 8

> n=length(x)

> x[n-3] — 3rd element from end of vector

[1] “May”

**Vector Modifications in R**

> x<-seq(2,10,1)
> x

[1] 2 3 4 5 6 7 8 9 10

> x[3]<- -4
> x

[1] 2 3 -4 5 6 7 8 9 10

**Sorting Vectors:**

We can sort elements of vector using sort function.

> x

[1] 2 3 -4 -5 6 7 8 9 10

> sort(x)

[1] -5 -4 2 3 6 7 8 9 10

> sort(x,decreasing=TRUE)

[1] 10 9 8 7 6 3 2 -4 -5