Skip to content
Vectors — Everything Is One
step 1/5

Reading — step 1 of 5

Learn

~1 min readThe Vector Mindset

In R, a single number is a vector of length 1. There are no scalars. This is the most important fact about R.

Create a vector with c() (combine):

ages <- c(25, 30, 35, 40)
length(ages)         # 4
ages[1]              # 25  (1-indexed!)
ages[2:3]            # 30 35
ages[c(1, 3)]        # 25 35
ages[-1]             # 30 35 40 (negative = exclude)

Operations are vectorized — they apply to every element automatically:

ages + 1             # 26 31 36 41
ages * 2             # 50 60 70 80
ages > 30            # FALSE FALSE TRUE TRUE
sum(ages)            # 130
mean(ages)           # 32.5

This is why R feels different — you almost never write loops. You write vectorized expressions.

Useful generators:

1:10                 # 1 2 3 4 5 6 7 8 9 10
seq(0, 1, by=0.25)   # 0.00 0.25 0.50 0.75 1.00
rep("x", 3)          # "x" "x" "x"

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…