R — Modeling records with named lists
In R, a named list can hold the fields of a record. Retrieve the quantity and unit price by name to calculate a line item’s subtotal.
A simple example
Read one field
- Start with A point with x = 2
- Do this Read x
- Result 2
point <- data.frame(x = 2)
cat(point$x)
2
Represent an invoice line
A named list can hold fields of different types. The constructor gives both fields stable names, and a separate function reads them by name to calculate the subtotal.
A café invoice lists three juices at 125 cents each. Store the quantity and price together, then calculate the subtotal when the receipt is printed. Changing the quantity can then update the total automatically.
Run the example
R 4. Run these commands from the directory containing the example.
Rscript Lesson.R
line_item <- function(units, cents) {
list(units = units, cents = cents)
}
subtotal <- function(item) {
item$units * item$cents
}
line <- line_item(3L, 125L)
cat(subtotal(line), "\n", sep = "")
375
The line holds three units at 125 cents each. Multiplication gives 375 cents. Keeping the subtotal derived means there is no third field that can become stale.
Try it yourself
Create a second line with two units at 90 cents each.
Check your answer
Its subtotal is 180 cents. The two subtotals together are 555 cents before any taxes or delivery charges.