If you've used any programming language, you know variables hold single values. But what if you need to store a bunch of numbers โ like test scores or temperatures? You could create ten separate variables, but that gets ugly fast. Vectors are R's answer. They're the simplest way to group values, and honestly, you'll use them constantly.
The c() Function โ Your New Best Friend
c() stands for "combine" or "concatenate." You throw values inside, separated by commas, and R bundles them into a vector. All values in a vector must be the same type โ numbers, characters, or logicals. Mix them and R will silently convert everything to the most flexible type.
# Creating vectors with c()
scores <- c(88, 92, 79, 94, 85)
names <- c("Alice", "Bob", "Charlie")
mixed <- c(1, "hello", TRUE)
print(scores)
print(names)
print(mixed)
Try it Yourself โ
Indexing โ Remember, R Starts at 1
Here's the biggest gotcha for anyone coming from Python or C: R uses 1-based indexing. The first element is at position 1, not 0. Use square brackets [] to pull out elements by position. You can also pass a vector of indices to grab multiple items at once.
scores <- c(88, 92, 79, 94, 85)
# R is 1-based!
print(scores[1])
print(scores[3])
# Multiple indices
print(scores[c(1, 3, 5)])
# Everything except position 2
print(scores[-2])
Try it Yourself โ
Generating Sequences with seq() and rep()
Typing c(1, 2, 3, 4, 5) works, but it's tedious. Use seq() for sequences with a start, end, and optional step size. Use rep() to repeat values. The colon operator : is a handy shortcut for simple integer sequences.
# Quick sequence with colon
1:10
# seq() gives you control
seq(from = 0, to = 100, by = 10)
# rep() repeats values
rep(c("A", "B"), times = 3)
rep(c("A", "B"), each = 3)
Try it Yourself โ