A vector is a column
◈ 10 cardsamount4 <- c(420, 180, 760, 250) is a column; amount4 * 1.13 multiplies every element at once — [1] 474.6 203.4 858.8 282.5 — with no fill-down. 1:4, seq() and rep() build vectors; a shorter vector is recycled, with a warning only when the lengths do not divide.
The column, without the sheet
A spreadsheet column is a list of values in order. R's word for that is a vector, and c() — combine — builds one:
> amount4 <- c(420, 180, 760, 250)
> amount4
[1] 420 180 760 250
> length(amount4)
[1] 4
Four values, one object. length() is the number of elements — the spreadsheet's COUNT of the column.
Worked example — the HST column with no fill-down
Module 5 built an HST-inclusive column by writing =D2*1.13 in one cell and filling it down twelve rows. In R the multiplication is vectorised: it applies to every element at once, and there is nothing to fill.
> amount4 * 1.13
[1] 474.6 203.4 858.8 282.5
Every arithmetic operator and most functions work this way: amount4 / 100, amount4 - 50, round(amount4 * 1.13). sum(amount4) is 1610 and amount4 / sum(amount4) is each order's share of the four — one line, four shares.
Three more ways to build a vector
> 1:4
[1] 1 2 3 4
> seq(0, 1500, by = 300)
[1] 0 300 600 900 1200 1500
> rep("ON", 3)
[1] "ON" "ON" "ON"
: is the integer run — 1:4 is four values, not the two numbers 1 and 4. seq(from, to, by =) is the run with a step — those are Module 4's histogram bin edges. rep() repeats. Notice the second line: the values are padded so the columns align, which is how R prints any vector with mixed widths.
Recycling
Add a vector of two to a vector of four and R recycles the shorter one — silently, because 4 is a multiple of 2:
> amount4 + c(1, 2)
[1] 421 182 761 252
1 was added to the first and third elements, 2 to the second and fourth. That is what amount4 * 1.13 was doing all along: 1.13 is a vector of length one, recycled four times. When the lengths do not divide, R still recycles — and warns:
> amount4 + c(1, 2, 3)
[1] 421 182 763 251
Warning message:
In amount4 + c(1, 2, 3) :
longer object length is not a multiple of shorter object length
A warning is not an error: the result was produced (the 1 wrapped round to the fourth element) and it is almost certainly not what was meant. Read warnings.
One last thing about c(): every element of a vector has the same type. Mix a number and a piece of text and the number gives way — c(1, "a") prints "1" "a", both text. Lesson 9.4 is about that.
Type three lines, then reproduce the HST column in Python
Type the vector, the vectorised multiplication and the seq(). The code block does the ×1.13 with a list comprehension — Python's vectorised line.
CRISP-DM: building a vector is data understanding → collect initial data in miniature; the arithmetic on it is data preparation → construct data.