Lesson contents

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

  1. Start with A point with x = 2
  2. Do this Read x
  3. Result 2
A record keeps related values together. Here the program reads a single named field.
Lesson.R
point <- data.frame(x = 2)
cat(point$x)
Output
2
Advertisements

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.

One line item: 3 juices. Price per juice: 125¢. Subtotal: 375¢.
Keep an invoice line together

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
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 = "")
Output
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.

An Introduction to R

Related tags

  • R
  • data modeling
  • records
  • methods