Skip to content
Lesson 3 of 9

Step 1 of 5 · Reading · ~2 min

Learn

The 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, not "count from the end")

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

Note ages > 30: a comparison against a vector returns a vector of logicals, one per element - not a single TRUE, and not the matching elements. Filtering is the separate step ages[ages > 30].

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"
ages[100]            # NA - past the end is a missing value, not an error

That last line is the trap. R will not stop you at the end of a vector, so a typo'd index does not crash; it puts NA into your data and the mistake surfaces three steps later.

Writing numbers out in the shape you meant

Two cat behaviours cost more beginner time than anything else in R.

cat separates its arguments with a space - including before a newline argument - and it does not pad decimals. round(x, 3) produces the number 20, which still prints as 20. If you need a fixed count of decimals, build the text with sprintf instead:

cat("sum:", 31, "\n")             # "sum: 31 \n"  - space before the newline
cat("sum: ", 31, "\n", sep="")    # "sum: 31\n"
round(20, 3)                          # 20      - still the number 20
sprintf("mean: %.3f", 20)             # "mean: 20.000"
sprintf("mean: %.3f", 3.875)          # "mean: 3.875"

round changes the value; sprintf decides how the value is written. Only the second can give you trailing zeros.

Up nextIf/Else and ComparisonControl Flow

Discussion

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

Sign in to post a comment or reply.

Loading…