๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Vectors

A vector is an ordered set of values that all share one type. One vector can hold many values under a single name.

A numeric vector

c combines four numbers into one vector. The print shows the values in their given order.

scores <- c(10, 20, 30, 40)
print(scores)

A character vector

This vector holds four pet names as text. The print shows the names in their given order.

pets <- c("cat", "dog", "fox", "hen")
print(pets)

One value has length 1

A single stored number forms a vector on its own. Its length is 1.

one <- 42
print(length(one))

One type wins

Each line mixes values of different types into one vector. One type wins in each vector and every value follows that type.

print(c(1, "a"))
print(c(1, TRUE))

Example

first <- 5
second <- 15
third <- 25
vals <- c(first, second, third)
print(vals)

Key points

  • c() combines values into a vector.
  • The values in a vector keep the order they were given in.
  • A single value on its own is a vector of length 1.
  • When mixed types are combined, one type wins and every value is converted to it.
  • A vector can be built from values already stored in variables.
  • Most data work in R is vector work.

In this example, three stored numbers are combined into one vector with c(). Print shows the values in the order they were combined.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does c(2, 4, 6) build?