How to Look at the Structure of Vectors in R - dummies

How to Look at the Structure of Vectors in R

By Andrie de Vries, Joris Meys

A vector is a one-dimensional set of values, all the same type. It’s the smallest unit you can work with in R. A single value is technically a vector as well — a vector with only one element. In mathematics vectors are almost always used with numerical values, but in R they also can include other types of data, like character strings.

R gives you an easy way to look at the structure of any object. This method comes in handy whenever you doubt the form of the result of a function or a script you wrote. To take a peek inside R objects, use the str() function.

The str() function gives you the type and structure of the object.

Take a look at the vector baskets.of.Granny:

> str(baskets.of.Granny)
 num [1:6] 12 4 5 6 9 3

R tells you a few things here:

  • First, it tells you that this is a num (numeric) type of vector.

  • Next to the vector type, R gives you the dimensions of the vector. This example has only one dimension, and that dimension has indices ranging from 1 to 6.

  • Finally, R gives you the first few values of the vector. In this example, the vector has only six values, so you see all of them.

If you want to know only how long a vector is, you can simply use the length() function, as follows:

> length(baskets.of.Granny)
[1] 6

Vectors in R can have other types as well. If you look at the vector authors, for example, you see a small difference:

> authors <- c("Andrie", "Joris")
> str(authors)
 chr [1:2] "Andrie" "Joris"

Again, you get the dimensions, the range of the indices, and the values. But this time, R tells you the type of vector is chr, or character.

The following types are common types of vectors:

  • Numeric vectors, containing all kind of numbers.

  • Integer vectors, containing integer values. (An integer vector is a special kind of numeric vector.)

  • Logical vectors, containing logical values (TRUE and/or FALSE)

  • Character vectors, containing text

  • Datetime vectors, containing dates and times in different formats

  • Factors, a special type of vector to work with categories.

R makes clear distinctions among these types of vectors, partly for reasons of logic. Multiplying two words, for example, doesn’t make sense.