Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 39 ยท Data Types and Structures

Vectors in R

Master R vectors, the core data structure. Create them with c(), seq() and rep(), index with positions, names and conditions, and use vectorized math and recycling.

The vector is the most important structure in R. A vector is an ordered sequence of values that all have the same type: all numbers, all text, or all TRUE/FALSE values. Even a single number such as 5 is a vector of length one. Almost everything else in R, from data frames to model results, is built out of vectors.

Learning to think in vectors is what makes R code short. Instead of writing a loop that handles one value at a time, you write one expression that handles all of them. This lesson shows how to create vectors, pick values out of them, and compute with them.

Creating vectors

Combine values with c():

R
ages    <- c(23, 31, 45, 19)
fruits  <- c("apple", "pear", "plum")
passed  <- c(TRUE, FALSE, TRUE)

length(ages)
#> [1] 4

Shortcuts for common sequences:

R
1:5
#> [1] 1 2 3 4 5

10:7
#> [1] 10  9  8  7

seq(0, 1, by = 0.25)
#> [1] 0.00 0.25 0.50 0.75 1.00

seq(1, 10, length.out = 4)
#> [1]  1  4  7 10

rep("ha", times = 3)
#> [1] "ha" "ha" "ha"

rep(c("a", "b"), each = 2)
#> [1] "a" "a" "b" "b"
  • a:b counts by one.
  • seq() gives control over the step (by) or the number of values (length.out).
  • rep() repeats values, either whole (times) or element by element (each).

c() also joins vectors together:

R
c(1:3, 10, c(20, 30))
#> [1]  1  2  3 10 20 30

One type per vector

Because every element must share a type, R coerces mixed input to the most flexible type. Text beats numbers, and numbers beat logicals:

R
c(1, "two", TRUE)
#> [1] "1"    "two"  "TRUE"

Everything became text. We study this rule in detail in Data Types and Coercion. Use lists when you need to mix types.

Indexing: picking elements out

Square brackets select elements. R counts from 1.

R
x <- c(10, 20, 30, 40, 50)

x[2]
#> [1] 20

x[c(1, 3)]
#> [1] 10 30

x[2:4]
#> [1] 20 30 40

x[-1]          # everything except the first
#> [1] 20 30 40 50

x[-c(1, 5)]    # drop first and last
#> [1] 20 30 40

Positive numbers keep, negative numbers drop. You cannot mix the two in one call.

Logical indexing

Put a logical vector inside the brackets and R keeps the elements where it is TRUE:

R
x > 25
#> [1] FALSE FALSE  TRUE  TRUE  TRUE

x[x > 25]
#> [1] 30 40 50

x[x > 15 & x < 45]
#> [1] 20 30 40

This pattern, filter by a condition, appears in almost every analysis. which() returns the positions instead:

R
which(x > 25)
#> [1] 3 4 5

Changing elements

R
x[2] <- 99
x
#> [1] 10 99 30 40 50

x[x > 40] <- 0
x
#> [1] 10  0 30 40  0

Assigning beyond the end grows the vector, and gaps are filled with NA (missing).

Named vectors

Elements can have names, and you can index by name:

R
ages <- c(Ana = 28, Ben = 35, Cleo = 41)
ages
#> Ana  Ben Cleo 
#>  28   35   41 

ages["Ben"]
#> Ben 
#>  35 

names(ages)
#> [1] "Ana"  "Ben"  "Cleo"

Names make small lookup tables easy. Use ages[["Ben"]] to get the bare number without its name.

Vectorized operations

Arithmetic and most functions work on every element at once:

R
prices <- c(4, 10, 25)

prices * 1.2
#> [1]  4.8 12.0 30.0

prices + c(1, 2, 3)
#> [1]  5 12 28

sqrt(c(1, 4, 9))
#> [1] 1 2 3

Summary functions turn a vector into one number:

Function Result
sum(x), mean(x), median(x) Total, average, middle value
min(x), max(x), range(x) Smallest, largest, both
length(x) Number of elements
cumsum(x) Running total
rev(x) Reversed
sort(x) Sorted ascending (decreasing = TRUE for descending)
order(x) Positions that would sort x
R
cumsum(1:5)
#> [1]  1  3  6 10 15

sort(c(3, 1, 2), decreasing = TRUE)
#> [1] 3 2 1

order(c(30, 10, 20))
#> [1] 2 3 1

Recycling

When two vectors have different lengths in an operation, R recycles the shorter one by repeating it:

R
1:6 + c(10, 20)
#> [1] 11 22 13 24 15 26

The c(10, 20) was repeated three times. A single number is recycled to any length, which is why x * 2 works. If the longer length is not a multiple of the shorter one, R still computes the answer but warns you:

R
1:5 + c(10, 20)
#> [1] 11 22 13 24 15
#> Warning message:
#> longer object length is not a multiple of shorter object length

Recycling is silent when the lengths divide evenly. If you accidentally compare vectors of different lengths, R gives a result without complaint. Check lengths with length() when something looks wrong.

Membership and uniqueness

R
letters[1:5]
#> [1] "a" "b" "c" "d" "e"

"c" %in% letters[1:5]
#> [1] TRUE

unique(c(3, 1, 3, 2, 1))
#> [1] 3 1 2

table(c("a", "b", "a", "a"))
#> 
#> a b 
#> 3 1 

%in% tests membership, unique() removes duplicates, and table() counts how often each value occurs. letters and LETTERS are built-in vectors of the alphabet.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does x[-1] return?

    A negative index drops that position and keeps the rest.
  2. 2. What is c(1, "a", TRUE)?

    A vector holds one type, so R coerces every element to character.
  3. 3. With x <- c(5, 12, 8, 20), what does x[x > 7] return?

    The logical index keeps elements where the condition is TRUE. Use which() for positions.
  4. 4. What does 1:4 * c(1, 10) return?

    The shorter vector is recycled: 11, 210, 31, 410 gives 1 20 3 40.
  5. 5. Which call returns "a" "a" "b" "b"?

    each repeats every element in turn, times repeats the whole vector.

Summary

  • A vector is an ordered collection of values of one type; single values are vectors of length one.
  • Build them with c(), :, seq() and rep().
  • Index with positions, negative positions, names or logical conditions; counting starts at 1.
  • Operations are vectorized, and shorter vectors are recycled.
  • sum(), mean(), sort(), which(), %in%, unique() and table() are the everyday tools.

Next: Data Types and Coercion