Vectors
Reviewed & published by Brayan K
A vector is R's most fundamental data structure — an ordered collection of values of the same type, like a single column of numbers, that R can operate on all at once.
Part of the free R course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.
By the end of this lesson you'll create vectors with c() and sequences, pick elements out by position and by condition, and use vectorized math to transform whole vectors in a single line.
What You'll Learn in This Lesson
- How to create vectors with c(), 1:n, seq(), and rep()
- Why every vector holds a single type
- How to index from position 1 with square brackets
- How to select elements with a logical condition
- How vectorized math applies to every element at once
- How summary functions reduce a vector to one value
1️⃣ Creating Vectors
The workhorse is c(), which combines values into a vector. For regular patterns, 1:5 makes a sequence, seq() gives you control over the step, and rep() repeats values.
# A vector is an ordered collection of values of the SAME type.
# Build one with c() ("combine").
ages <- c(25, 30, 22, 41, 35)
ages # -> [1] 25 30 22 41 35
# Sequences are quick to make:
1:5 # -> [1] 1 2 3 4 5
seq(0, 10, by = 2) # -> [1] 0 2 4 6 8 10
rep("hi", 3) # -> [1] "hi" "hi" "hi"
# length() counts the elements:
length(ages) # -> [1] 52️⃣ Indexing: Picking Elements
Use square brackets to pull out elements. R indexes from 1. You can ask for a single position, several positions, a range, everything except some positions (with a minus), or — most powerfully — every element that passes a logical test.
# R indexing starts at 1 (not 0). Use square brackets [ ].
scores <- c(88, 95, 70, 60, 100)
scores[1] # first element -> [1] 88
scores[c(1, 3)] # several at once -> [1] 88 70
scores[2:4] # a range -> [1] 95 70 60
scores[-1] # drop the first -> [1] 95 70 60 100
# Logical indexing: keep only elements that pass a test
scores[scores >= 90] # -> [1] 95 100That last line — scores[scores >= 90] — is the pattern you'll use constantly: filter a vector down to the values that meet a condition.
3️⃣ Vectorized Math
Operations apply to every element automatically — no loop required. You can combine a vector with a single number (R repeats the number) or with another vector (element by element). Summary functions like sum() and mean() collapse a vector to one value.
# Vectorized math: an operation applies to EVERY element at once.
prices <- c(10, 20, 30)
prices * 1.2 # add 20% to each -> [1] 12 24 36
prices + 5 # add 5 to each -> [1] 15 25 35
# Two vectors combine element by element:
a <- c(1, 2, 3)
b <- c(10, 20, 30)
a + b # -> [1] 11 22 33
# Summary functions reduce a vector to one number:
sum(prices) # -> [1] 60
max(prices) # -> [1] 30
mean(prices) # -> [1] 20Your turn. Fill in the ___ blank, run it, and compare with the expected output.
# 🎯 YOUR TURN — replace each ___ then run it.
# 1) Make a vector of five test scores
scores <- ___ # 👉 replace ___ with c(70, 85, 90, 65, 88) (or five scores of your own)
# 2) Print only the scores that are 80 or higher (logical indexing)
high <- scores[scores >= 80]
print(high)
# 3) Print the average of the high scores, rounded to 1 decimal
cat("Average of high scores:", round(mean(high), 1), "\n")
# ✅ Expected output (for c(70, 85, 90, 65, 88)):
# [1] 85 90 88
# Average of high scores: 87.7Mini-Challenge: Weekly Steps
Write it from the outline, run it, and check it against the example output. The sum(steps > 8000) trick is worth remembering — comparing a vector gives TRUE/FALSE, and summing them counts the TRUEs.
# 🎯 MINI-CHALLENGE: weekly steps analysis.
#
# 1. Create a vector of 7 daily step counts.
# 2. Print the total steps for the week with sum().
# 3. Print the busiest day's count with max().
# 4. Print how many days you walked more than 8000 steps
# (hint: sum(steps > 8000) counts the TRUEs).
#
# ✅ Example output:
# Total: 56000
# Best day: 12000
# Active days: 3
# your code hereCommon Errors (and the fix)
- Off-by-one from 0-indexing habits — x[0] returns an empty vector, not the first element. The first element is x[1].
- Numbers turned into text — c(1, 2, "3") coerces everything to character. Keep one type per vector; check with class().
- "longer object length is not a multiple..." — a recycling warning when two vectors don't divide evenly. Make their lengths match, or recycle on purpose.
- NA spreading through math — if a vector contains NA, mean(x) returns NA. Use mean(x, na.rm = TRUE) to skip missing values.
Pro Tips
- 💡 Think in whole vectors: if you're tempted to write a loop, ask whether a vectorized operation does it in one line.
- 💡 Name your elements: c(a = 1, b = 2) lets you index by name — x["a"].
- 💡 Count conditions fast: sum(x > 10) counts matches, mean(x > 10) gives the proportion.
📋 Quick Reference — Vectors
| Task | R Syntax |
|---|---|
| Create a vector | c(1, 2, 3) |
| Sequence | seq(0, 10, by = 2) |
| First element | x[1] |
| Filter by condition | x[x > 5] |
| Count of elements | length(x) |
| Sum / average | sum(x); mean(x) |
🎉 Lesson Complete!
- ✅ A vector is an ordered collection of one type, built with c()
- ✅ R indexes from 1 using square brackets
- ✅ Logical indexing — x[x > 5] — filters a vector
- ✅ Math is vectorized: it applies to every element at once
- ✅ sum(), mean(), max() summarise a vector
Practice quiz
Which function combines values into a vector in R?
- vector()
- c()
- list()
- combine.all()
Answer: c(). c() ('combine') builds a vector from individual values.
What does 1:5 produce?
- c(1, 2, 3, 4, 5)
- c(1, 5)
- c(0, 1, 2, 3, 4)
- An error
Answer: c(1, 2, 3, 4, 5). The colon makes the integer sequence 1, 2, 3, 4, 5.
What does seq(0, 10, by = 2) return?
- c(0, 10)
- c(2, 4, 6, 8, 10)
- c(0, 5, 10)
- c(0, 2, 4, 6, 8, 10)
Answer: c(0, 2, 4, 6, 8, 10). seq() steps from 0 to 10 in increments of 2.
At what index does R start counting?
- At 0
- At -1
- At 1
- At the last element
Answer: At 1. R is 1-indexed: x[1] is the first element.
What does scores[scores >= 90] do?
- Counts elements >= 90
- Keeps only the elements that are 90 or greater
- Returns positions
- Returns TRUE/FALSE
Answer: Keeps only the elements that are 90 or greater. Logical indexing keeps elements where the test is TRUE.
What does length(ages) return?
- The number of elements in the vector
- The sum of the elements
- The largest element
- The vector itself
Answer: The number of elements in the vector. length() counts how many elements a vector has.
What does c(1, "a") become?
- A list
- An error
- Numeric
- A character vector (everything coerced to character)
Answer: A character vector (everything coerced to character). A vector holds one type; R coerces to the most flexible type, here character.
What does c(1, 2, 3, 4) + c(10, 20) give?
- c(11, 22)
- An error
- c(11, 22, 13, 24)
- c(11, 22, 33, 44)
Answer: c(11, 22, 13, 24). R recycles the shorter vector: 1+10, 2+20, 3+10, 4+20.
What does sum(x > 8000) compute?
- The total of all values
- The count of elements greater than 8000
- The mean of x
- The max of x
Answer: The count of elements greater than 8000. Comparing gives TRUE/FALSE; summing counts the TRUEs.
What does x[0] return in R?
- The first element
- An error
- NULL
- An empty vector
Answer: An empty vector. Index 0 selects nothing, returning a length-0 (empty) vector.
Continue this course
- Previous: RStudio & Running Code
- Next: Operators — Arithmetic, comparison, and logical operators with vectorized behaviour
- Quick reference: R cheat sheet › Basics & Vectors
Frequently asked questions
Why does R put [1] in front of my output?
That [1] is the position (index) of the first value on that line. Because R is vector-based, every result is really a vector — even a single number is a vector of length 1. When a vector is too long to fit on one line, R wraps it and prints the starting index of each line, so you might see [1] at the start and, say, [11] further down. It's a navigation aid, not an error.
Does R really start counting at 1, not 0?
Yes. Unlike most programming languages, R indexes from 1, so x[1] is the first element. This matches how statisticians and spreadsheets count and is one of R's friendliest features for non-programmers. Just remember it when moving between R and languages like Python or JavaScript, which start at 0.
What happens if I mix types in c()?
A vector can only hold one type, so R silently 'coerces' everything to the most flexible type present. c(1, "a") becomes character ("1" and "a"), and c(1, TRUE) becomes numeric (1 and 1). This is handy but can surprise you — if a numeric vector suddenly shows quotes, a stray piece of text turned the whole thing into characters. Use class() to check.
What is recycling when adding two vectors?
If you combine vectors of different lengths, R 'recycles' the shorter one — repeating it to match the longer. So c(1, 2, 3, 4) + c(10, 20) gives 11, 22, 13, 24. When the longer length isn't a multiple of the shorter, R still recycles but warns you. Recycling is powerful (it's why prices + 5 works) but be deliberate about it to avoid silent bugs.