R Vectors

A vector is R's basic container for a sequence of values of the same type, and mastering it unlocks nearly everything else in the language.

What Is a Vector?

A vector is an ordered collection of values that all share the same type - all numbers, all text, or all logical values. You build one with the c() function, short for combine. Vectors are the default shape of data in R: even a single number like 7 is technically a vector of length one.

Example

scores <- c(88, 92, 76, 95, 60)
scores

fruits <- c("apple", "pear", "fig")
fruits

length(scores)

Giving Vector Elements Names

You can attach a name to each element of a vector, which makes it easier to read and lets you pull out values by label instead of position. Names are set inside c() or added afterward with the names() function.

Named Vector

inventory <- c(pens = 40, notebooks = 15, erasers = 22)
inventory

inventory["notebooks"]
names(inventory)

Indexing: Pulling Out Elements

R indexes vectors starting at 1, not 0. You can select elements by position, by a range, by name, or by a logical condition. Negative indices tell R to exclude an element rather than select it.

  • scores[1] - the first element
  • scores[2:4] - elements two through four
  • scores[-1] - every element except the first
  • scores[scores > 80] - every element that satisfies a condition
  • inventory["pens"] - the element named "pens"

Indexing Examples

scores <- c(88, 92, 76, 95, 60)

scores[1]
scores[2:4]
scores[-1]
scores[scores > 80]
Note: Operations on vectors are vectorized - scores + 5 adds 5 to every element in one step, no loop required. Leaning on this is one of R's biggest strengths and makes code shorter and faster.
FunctionWhat it does
length(x)Number of elements in x
sum(x)Total of all elements
mean(x)Average of all elements
sort(x)Elements in ascending order
rev(x)Elements in reverse order

Exercise: R Vectors

Which function combines individual values into a vector in R?