Introduction and Assignment

Introduction and Assignment in R: --- In a fruit packhouse nobody ever handles a loose apple.


The Analogy: The Apple Packhouse Grading Line

In a fruit packhouse nobody ever handles a loose apple. Fruit comes off the lorry in moulded trays, and a tray is the smallest unit the line will accept. If a grower brings in one prize apple for inspection, the foreman still drops it into a tray of its own and chalks the count 1 on the end board, because every machine on that line -- the brusher, the waxer, the sizing gate -- is built to swallow a tray and hand a tray to the next station. There is no slot anywhere on the line shaped like a single apple. The tray of one is not a special case the line tolerates; it is the ordinary case, and the line has no other.

A tray also holds exactly one commodity, and the reason is not tidiness. The sizing gate is calibrated for one fruit at a time, so apples travel with apples and pears with pears. When a pear does end up in an apple tray nobody stops the line to pick it out. The foreman crosses out the label and chalks MIXED, and from that moment the tray is treated as the least specific thing it contains: it can no longer pass the apple sizer, so it is routed to juice. One stray pear silently demotes forty good apples, and the demotion is recorded nowhere except on the end board.

Every tray carries its destination chalked on the end board as an arrow, -> BIN 4. The arrow earns its keep. It says the contents move into the bin and not the other way about, so a supervisor walking the line reads direction at a glance without having to know what is in either one. Re-chalking a tray costs nothing and happens twenty times a shift; the bin names painted on the wall never change. Trainees who write the arrow backwards, or who write an equals sign because it is quicker, produce boards that are technically legible and take twice as long to audit.

The failure mode is quiet, and it is arithmetic. The brusher applies its instruction to a whole tray at once, so when two trays of unequal count are run against each other -- twelve against three -- the line does not stop. It cycles the short tray round again, 1-2-3-1-2-3-1-2-3-1-2-3, until the long tray is satisfied. If the counts divide evenly nobody notices, and in fairness the pairing was usually what the foreman intended. If they do not divide evenly the line still finishes the job, having used part of the short tray twice, and the only trace is a slip in the foreman's book that nobody reads until the month-end reconciliation is out by a number that makes no sense. The mistake was three days upstream and there is nothing in the output to point at it.


Syntax or Core Structure

Three facts sit underneath everything else in R, and the block below is all three at once. Assignment points leftward with an arrow. There is no such thing as a single value, only a vector that happens to have length 1. And a vector holds one type, so combining types does not fail -- it converts.

# --- Assignment: the arrow points from the value to the name ---
analyst <- "Data Scientist"
years   <- 28L
ratio   <- 3.5

cat(sprintf("analyst : %s\n", analyst))
cat(sprintf("years   : %d\n", years))
cat(sprintf("ratio   : %.1f\n", ratio))

# --- There are no scalars: each of those is a vector of length 1 ---
cat(sprintf("length(analyst) = %d\n", length(analyst)))
cat(sprintf("class(years)    = %s\n", class(years)))

# --- c() combines into a longer vector of exactly one type ---
grades <- c(85L, 92L, 78L, 90L)
cat(sprintf("n = %d  sum = %d  mean = %.2f\n",
            length(grades), sum(grades), mean(grades)))

# --- One instruction, applied to the whole tray ---
curved <- grades + 5
cat(sprintf("curved: %s\n", paste(curved, collapse = " ")))

# --- A tray holds one commodity: mixing types re-labels the tray ---
mixed <- c(1L, 2L, "three")
cat(sprintf("class(mixed) = %s\n", class(mixed)))
cat(sprintf("mixed[1] is now the text %s\n", mixed[1]))

Output:

analyst : Data Scientist
years   : 28
ratio   : 3.5
length(analyst) = 1
class(years)    = integer
n = 4  sum = 345  mean = 86.25
curved: 90 97 83 95
class(mixed) = character
mixed[1] is now the text 1

One note on the printing style, because every lesson in this track uses it. R's cat glues its arguments together with a separator, and the default separator is a single space -- including the gap between the last value and the newline you passed as a final argument. So cat("total:", v, "\n") emits a line that ends in a space, which is invisible on screen and very visible in a diff or a test fixture. Building the line with sprintf and handing cat exactly one string avoids the whole problem.

v <- c(1L, 2L, 3L)

# cat("total:", v, "\n") would put a space between every argument, and
# therefore also between the final 3 and the newline. Build the line instead:
cat(sprintf("total: %s\n", paste(v, collapse = " ")))

Output:

total: 1 2 3

Technical Depth: Atomic Types, Coercion, and the Recycling Rule

The six atomic types

Everything in R is built from six atomic vector types. class() is the friendly answer and typeof() is the true one; they disagree for numbers, where class() says numeric for both integer and double vectors.

TypeWhat typeof returnsA literal you can typeWhat one slot holds
logicallogicalTRUE, FALSE, NAa truth value or the absence of one
integerinteger42La whole number, signed, 32-bit
doubledouble42, 4.2e1, 1/3an IEEE 754 binary64 number
charactercharacter"gauge 4"a whole string, never a single char
complexcomplex3+2ia real part and an imaginary part
rawrawas.raw(255)one byte, printed as two hex digits

The distinction between integer and double is not cosmetic. Integers are exact and they overflow; doubles are approximate and they saturate to Inf.

cat(sprintf("integer max : %d\n", .Machine$integer.max))

over <- suppressWarnings(.Machine$integer.max + 1L)
cat(sprintf("one more    : %s\n", ifelse(is.na(over), "NA", format(over))))

cat(sprintf("as a double : %.0f\n", .Machine$integer.max + 1))
cat(sprintf("typeof(1)   = %s   typeof(1L) = %s\n", typeof(1), typeof(1L)))
cat(sprintf("class(1)    = %s   class(1L)  = %s\n", class(1), class(1L)))

Output:

integer max : 2147483647
one more    : NA
as a double : 2147483648
typeof(1)   = double   typeof(1L) = integer
class(1)    = numeric   class(1L)  = integer

The overflow above emits the warning NAs produced by integer overflow on stderr; suppressWarnings is used only so the transcript above is exactly the stdout lines.

Coercion: the tray takes the least specific label

When c() is handed a mixture, it does not complain and it does not keep both types. It promotes everything to the least specific type present, following a fixed ladder. Nothing is ever demoted, so the promotion is one-way and lossy in exactly one place: once a number becomes text, arithmetic on it is an error rather than a wrong answer.

Tray contentsResulting typeWhat happens to the first element
all logicallogicalTRUE stays TRUE
logical with integerintegerTRUE becomes 1
integer with doubledouble3L becomes 3
double with complexcomplex2.5 becomes 2.5 plus 0i
anything with charactercharacter2.5 becomes the text 2.5
show_type <- function(label, x) {
  cat(sprintf("%-22s -> %-9s first = %s\n", label, typeof(x), format(x[1])))
}

show_type('c(TRUE, FALSE)', c(TRUE, FALSE))
show_type('c(TRUE, 3L)',    c(TRUE, 3L))
show_type('c(3L, 2.5)',     c(3L, 2.5))
show_type('c(2.5, "a")',    c(2.5, "a"))

Output:

c(TRUE, FALSE)         -> logical   first = TRUE
c(TRUE, 3L)            -> integer   first = 1
c(3L, 2.5)             -> double    first = 3
c(2.5, "a")            -> character first = 2.5

That third line is the one that bites in real work. A column read from a CSV with a single stray value like n/a in it arrives as character, every arithmetic operation on it errors, and the fix is upstream in the reader rather than downstream in a coercion.

The recycling rule

When two vectors of different length meet an arithmetic operator, R does not stop. It repeats the shorter one until the longer one is satisfied. If the longer length is an exact multiple of the shorter, this is silent and is usually what you meant. If it is not, you get a warning and a result anyway.

long  <- c(10L, 20L, 30L, 40L, 50L, 60L)
short <- c(1L, 2L, 3L)

clean <- long + short                                # 6 is 2 x 3: silent
cat(sprintf("6 against 3 : %s\n", paste(clean, collapse = " ")))

ragged_src <- c(1L, 2L, 3L, 4L)
ragged <- suppressWarnings(long + ragged_src)        # 6 is not a multiple of 4
cat(sprintf("6 against 4 : %s\n", paste(ragged, collapse = " ")))
cat(sprintf("difference  : %s\n", paste(ragged - clean, collapse = " ")))

Output:

6 against 3 : 11 22 33 41 52 63
6 against 4 : 11 22 33 44 51 62
difference  : 0 0 0 3 -1 -1

The ragged case raises longer object length is not a multiple of shorter object length on stderr and then hands back six numbers as if nothing were wrong. Three of them agree with the clean pairing by coincidence, which is what makes this hard to spot: the first few rows of a spot check look right. Comparison operators recycle too, and length-2 against length-4 divides evenly, so this one is silent:

readings <- c(4L, 9L, 2L, 7L)
limits   <- c(5L, 5L)                                # meant to be one limit
cat(sprintf("over limit? : %s\n", paste(readings > limits, collapse = " ")))

Output:

over limit? : FALSE TRUE FALSE TRUE

That answer is correct here only because both limits happen to be 5. Had the second been 8, rows 2 and 4 would be compared against 8 and rows 1 and 3 against 5, with no warning at all.

Four ways to bind a name

FormReads asWhere the binding landsWhen to reach for it
x <- 5put 5 into xthe current environmentalways, for real assignment
x = 5x equals 5the current environmentnever at top level; it reads as an argument
5 -> xsend 5 into xthe current environmentthe tail of a long pipe, sparingly
x <<- 5reach out and set xthe nearest enclosing scope that already binds xalmost never outside a closure
assign("x", 5)set the name xwhichever environment you namewhen the name itself is computed at runtime

The reason to keep = out of assignment position is not style, it is that = and <- mean different things inside a function call. = names an argument; <- assigns a variable and passes its value.

mean_named <- mean(x = c(1, 2, 3, 4))                # names the argument
cat(sprintf("mean_named : %.1f\n", mean_named))

mean_side <- mean(x <- c(1, 2, 3, 4))                # assigns, then passes
cat(sprintf("mean_side  : %.1f (a variable x of length %d now exists too)\n",
            mean_side, length(x)))

counter <- 0L
bump <- function() {
  counter <<- counter + 1L                           # reaches the outer binding
  invisible(NULL)
}
bump(); bump(); bump()
cat(sprintf("counter    : %d\n", counter))

Output:

mean_named : 2.5
mean_side  : 2.5 (a variable x of length 4 now exists too)
counter    : 3

Real World Example: Reconciling a Day of Water-Meter Readings

Six zones of a district water network are read at the start and end of a day. The job is to work out consumption, classify anything that cannot be consumption, apply a two-band tariff, and print a report a billing clerk can sign. Written in a loop-heavy language this is thirty lines of index arithmetic; written in R the arithmetic is four lines and the loop exists only because printing is a side effect.

# --- A day's readings for six zones, in cubic metres -----------------------
zones   <- c("NORTH", "SOUTH", "EAST", "WEST", "CIVIC", "DEPOT")
open_r  <- c(10450L, 8300L, 15980L, 6120L, 22040L, 31875L)
close_r <- c(10712L, 8305L, 16455L, 6108L, 22040L, 32130L)

# --- One subtraction does all six zones ------------------------------------
delta <- close_r - open_r

# --- Classification, also vectorised: no loop, no if -----------------------
status <- ifelse(delta < 0L, "ROLLBACK",
                 ifelse(delta == 0L, "NO-USE", "OK"))
billable <- ifelse(status == "OK", delta, 0L)

# --- Two-band tariff: 1.85 for the first 200 units, 2.40 above that --------
charge_for <- function(units) {
  first_band  <- pmin(units, 200L)
  second_band <- pmax(units - 200L, 0L)
  first_band * 1.85 + second_band * 2.40
}
charges <- charge_for(billable)

# --- Report ----------------------------------------------------------------
row_fmt <- "%-6s %8d %8d %7d %-9s %10.2f\n"
rule    <- strrep("-", 53)

cat(sprintf("%-6s %8s %8s %7s %-9s %10s\n",
            "ZONE", "OPEN", "CLOSE", "DELTA", "STATUS", "CHARGE"))
cat(sprintf("%s\n", rule))
for (i in seq_along(zones)) {
  cat(sprintf(row_fmt, zones[i], open_r[i], close_r[i],
              delta[i], status[i], charges[i]))
}
cat(sprintf("%s\n", rule))
cat(sprintf("%-6s %8s %8s %7d %-9s %10.2f\n",
            "TOTAL", "", "", sum(billable), "", sum(charges)))

flagged <- zones[status != "OK"]
cat(sprintf("flagged       : %s\n", paste(flagged, collapse = ", ")))
cat(sprintf("billed volume : %d units against %d metered\n",
            sum(billable), sum(delta)))

Output:

ZONE       OPEN    CLOSE   DELTA STATUS        CHARGE
-----------------------------------------------------
NORTH     10450    10712     262 OK            518.80
SOUTH      8300     8305       5 OK              9.25
EAST      15980    16455     475 OK           1030.00
WEST       6120     6108     -12 ROLLBACK        0.00
CIVIC     22040    22040       0 NO-USE          0.00
DEPOT     31875    32130     255 OK            502.00
-----------------------------------------------------
TOTAL                        997              2060.05
flagged       : WEST, CIVIC
billed volume : 997 units against 985 metered

The arithmetic layer is three statements and none of them mentions an index. close_r - open_r produces all six differences at once because both operands are length 6, so the pairing is positional and the recycling rule never engages. The classification is two nested ifelse calls, each returning a full-length vector, and billable is a third. The only loop in the program exists to print, and even that is written with seq_along(zones) rather than 1:length(zones) so that an empty reading file produces no rows instead of one row indexed 1 and one indexed 0.

ifelse is not if with extra steps. if accepts a single condition and, since R 4.2, raises an error rather than a warning when handed a longer one, so it cannot classify a vector at all. ifelse takes a logical vector and two value vectors, recycles all three to the length of the condition, and picks element by element. The cost is that both branches are evaluated for every element before the selection happens, which is invisible here and expensive if a branch does real work; the other cost is that ifelse returns a bare vector and drops attributes, so feeding it a factor gives you back the integer codes rather than the labels.

The tariff shows the same shape one level down. pmin and pmax are the parallel, element-wise versions of min and max: pmin(units, 200L) clamps every zone at 200 and pmax(units - 200L, 0L) keeps only what spilled over, so the two bands are complementary full-length vectors that add up to the original. charge_for never learns how many zones there are. It works unchanged on one zone or ten thousand, which is the practical payoff of writing against whole vectors rather than against positions.

The report is also wrong, and it says so out loud. The last line admits billing 997 units against 985 metered, and that gap is the design flaw: the ROLLBACK branch zeroes a negative delta instead of interpreting it. A five-digit dial that runs past 99999 back to 00001 produces exactly the same negative number as a meter that was swapped, replaced, or tampered with, and nothing in the data distinguishes the two -- so a legitimate rollover is silently dropped from the bill while an illegitimate one is silently forgiven. Fixing it properly means passing the dial capacity in and reconstructing the reading as capacity minus open plus close, and refusing to produce a signed total on any day it cannot decide. Three smaller limits sit alongside it: status is three bare string literals compared later with ==, so a typo misclassifies silently instead of erroring; the NO-USE rule cannot tell a decommissioned meter from an idle one, so that flag accumulates until people stop reading it; and the charge column is doubles, which means the printed 2060.05 is correct while sum(charges) == 2060.05 is FALSE, because neither 1.85 nor 2.40 is exact in binary. Money belongs in integer pence with the division done once, at the end.


Common Mistakes

  1. Handing the newline to cat as its own argument. cat("total:", v, "\n") inserts the separator between every pair of arguments, so the line ends with a space before the newline. On screen it looks perfect. In a diff, a test fixture, or a file a downstream tool parses on width, it is a defect. Build the whole line with sprintf and pass cat exactly one string.
  1. Using = for assignment because it is one keystroke fewer. At top level it works, which is why the habit forms. Inside a function call it means something else entirely: f(x = 1) names an argument and f(x <- 1) creates a variable and passes its value. Code that mixes the two forces every reader to decide, at every call, which one was meant.
  1. Expecting c() to reject a mixture. It never rejects. It promotes to the least specific type present and returns quietly, so one n/a in a column of ten thousand numbers turns the whole column into text. The symptom appears far away, as an arithmetic error on a variable that was numeric yesterday.
  1. Leaning on recycling instead of stating it. Recycling is a feature when the shorter operand is length 1 and a trap at every other length. If you mean to apply a length-3 pattern to a length-12 vector, write rep(pattern, times = 4) so the intent is in the code and a length change breaks loudly.
  1. Using if where the condition is a whole column. if wants one TRUE or FALSE. Before R 4.2 it silently used the first element of a longer condition and got on with it; from R 4.2 it is an error. Either is bad news at 3am, and ifelse or dplyr::case_when is what the situation actually calls for.
  1. Growing a vector inside a loop. out <- c(out, value) allocates a new vector and copies the old one on every iteration, so the cost is quadratic in the number of iterations. Pre-allocate with numeric(n) or vector("list", n) and assign into position, or replace the loop with a vectorised expression.
  1. Comparing doubles with ==. 0.1 + 0.2 == 0.3 is FALSE, and so is nearly every equality test on a computed double. Use isTRUE(all.equal(a, b)) when you want tolerance, or keep the quantity in integers when you want exactness.
  1. Writing 1:length(x). When x is empty, length(x) is 0 and 1:0 is the two-element vector 1, 0 -- so the loop runs twice on an empty input and indexes out of range. seq_len(length(x)) and seq_along(x) both yield nothing, which is the correct answer.
  1. Assigning to T or F. TRUE and FALSE are reserved words but T and F are ordinary variables that happen to be pre-set. Any script, or any package you attach, can rebind them, and then every abbreviated logical in your code flips meaning without a single error message. Spell them out.

Best Practices

  • Use <- for every assignment and keep = for named arguments only. The visual distinction is the whole point: one glance tells you whether a line binds a name or configures a call.
  • Suffix integer literals with L whenever the value is a count, an index, or an identifier. It documents intent, halves the memory, and makes an accidental fractional value an error instead of a silent 3.0000001.
  • Prefer seq_len(n) and seq_along(x) to 1:n. The colon operator counts downwards when the upper bound is smaller, which is exactly what happens on empty input.
  • Let vectorisation do the looping and reserve for for genuine side effects such as printing or writing files. If a loop body is pure arithmetic, an operator or an apply variant will express it more clearly and run faster.
  • Build every line of output with sprintf and emit it with one cat. Fixed field widths make the result diffable, and the format string documents the report layout in one place.
  • Make recycling explicit with rep() when you want it, and assert lengths with stopifnot(length(a) == length(b)) when you do not. Silent recycling is the single most common source of quietly wrong numbers in R.
  • Keep money, counts, and anything that must reconcile in integer minor units, and divide once at the point of display. Doubles are for measurements, not for ledgers.
  • Check your assumptions at the top of a function with stopifnot(). It costs one line, fails at the boundary rather than three transformations later, and doubles as documentation of what the function accepts.

Practice Exercises

  1. Extend the meter reconciliation so that a ROLLBACK is interpreted rather than zeroed. Add a capacity argument of 100000L and reconstruct a rolled-over reading as capacity minus the opening reading plus the closing reading. Then add a rule that refuses to reconstruct when the implied consumption exceeds a plausible daily maximum of 5000 units, marking that zone REVIEW instead. Print a report whose billed volume and metered volume agree, and prove they agree with a stopifnot.
  1. Write a function type_ladder(...) that accepts any number of vectors, combines each adjacent pair with c(), and prints a fixed-width table of the two input types and the resulting type. Use it to confirm the full promotion ladder from logical through integer, double, complex and character, and add a row showing what happens when a raw vector meets an integer one -- the answer is not what the ladder suggests, and explaining why is the exercise.
  1. Write safe_add(a, b) that adds two vectors but refuses to recycle silently. It should return the sum when the lengths are equal, recycle without complaint when one operand has length 1, and stop with a message naming both lengths otherwise. Verify all three paths, including that the error message contains both numbers.
  1. Replace the two-band tariff with a three-band one -- 1.85 up to 200 units, 2.40 from 201 to 800, and 3.10 above 800 -- written so that the band boundaries and rates live in two vectors rather than in the function body. Compute the charge for consumptions of 150, 500 and 1200 units, hand-check each against the bands with a calculator, and assert the three results with stopifnot before printing them.