Vector Objects in R

A vector is a one-dimensional object in R. There is no class specific for a vector but a vector object can be one of several classes, most usually:

  • numeric
  • character
  • logical
  • complex

Your numeric vector can be given as double or integer. Note that a factor is not considered to be a vector.

You can make a blank vector using the vector() command:

vector(mode = "logical", length = 0)

For example:

> vl <- vector(mode = "logical", length = 3)
> vl
[1] FALSE FALSE FALSE

> vc <- vector(mode = "character", length = 5)
> vc
[1] "" "" "" "" ""

> vn = vector(mode = "numeric", length = 4)
> vn
[1] 0 0 0 0

> vi = vector(mode = "complex", length = 3)
> vi
[1] 0+0i 0+0i 0+0i

The blank vector you create can be “filled in” later:

> vi[1] <- 3+2i
> vi
[1] 3+2i 0+0i 0+0i

Notice though that the value you enter can either be coerced to the appropriate form or alter the class of the vector:

> vc[1] <- 23
> vc
[1] "23" "" "" "" ""

The value entered was a number (23) but the vector it is added to remains character in class. In the next example you create an integer vector:

> vi = vector(mode = "integer", length = 3)
> vi
[1] 0 0 0

> class(vi)
[1] "integer"

Adding a value can alter the class:

> vi[1] <- 2
> vi
[1] 2 0 0

> class(vi)
[1] "numeric"

In this case the value (2) is taken as a regular double precision numeric value. To force the value to remain an integer you need to use the as.integer() command:

> vi <- vector(mode = "integer", length = 3)
> vi[1] <- as.integer(2)
> vi
[1] 2 0 0

> class(vi)
[1] "integer"

Now the entered value keeps its integer class.

Comments are closed.