R as a calculator
◈ 8 cardsVectors, indexing, and a data frame — enough to read what the paper prints and predict what a line returns.
What you need, and no more
The paper prints R output; you read it. To read it fluently you need five things: how a vector is built, how it is indexed, two vector generators, how a data frame packages columns, and how a logical test is counted. Each is one line.
Worked example — eight invoices
Start with eight days-to-pay values.
> days <- c(12, 30, 7, 45, 18, 22, 9, 15)
> days[2]
[1] 30
> days[-2]
[1] 12 7 45 18 22 9 15
c() combines values into a vector; <- assigns it a name. Square brackets index it, starting at 1 (not 0). A negative index drops that element and returns the other seven — it does not reverse anything, and it does not return the second-from-last. The [1] at the start of an output line is the position of the first value printed on that line; when a long vector wraps, the next line starts with the index of its first value.
Two generators you will see in output:
> seq(0, 20, by = 5)
[1] 0 5 10 15 20
> rep("late", 3)
[1] "late" "late" "late"
seq(from, to, by =) is an arithmetic sequence; rep(x, times) repeats. Notice that R pads the numbers so the columns line up — the double space before 0 is alignment, not a value.
Now attach a payment channel to each invoice and put the two columns in a data frame — a table whose columns can be of different types:
> inv <- data.frame(days = days, channel = c("e","p","e","p","e","e","p","e"))
> inv$days[inv$channel == "p"]
[1] 30 45 9
inv$days pulls one column out as a plain vector. inv$channel == "p" is a logical vector — TRUE where the channel is paper — and using it as an index keeps only those positions: invoices 2, 4 and 7. That single line is how every "compare the groups" question on the paper slices its data.
Finally, counting with a logical test:
> sum(days > 20)
[1] 3
> length(days)
[1] 8
days > 20 is eight TRUE/FALSE values; sum treats TRUE as 1, so the line counts how many invoices took more than 20 days (30, 45 and 22). length is .
Reading habits
R is case-sensitive — Days is not days and produces an error, not a warning. Mixing positive and negative indices in one bracket is an error too. A printed [1] is not part of the answer. When a question asks "what does this line print?", first decide whether the result is one value or a vector, then apply the rule for that function.