2. Vectors

Learn R vectors, indexing, and vectorized arithmetic with live, editable R code.

A vector is Rโ€™s basic building block โ€” an ordered collection of values of the same type, made with c(). Arithmetic on vectors happens element-by-element. Indexing uses square brackets and starts at 1, not 0.

Discuss first

Before you run the code below: scores holds 5 values, and indexing starts at 1. What element do you expect scores[2] to return โ€” and how many values do you expect scores[scores > 85] to keep?

Edit the code below if you like, then press Run Code to check your answer.

Check your understanding

Q1. Given scores <- c(88, 92, 79, 95, 67), what does scores[1] return?

Q2. Fill in the blank: the idiomatic way to build the vector 1, 2, 3 is:

(1, 2, 3)
Back to top