R Language Self-Modifying Lists and $1 Chinese Food

Last weekend I drove from Seattle to Portland. That drive is often called The Slog because it’s 200 miles of boredom interspersed with unexpected moments of terror when, in a torrential downpour of rain, an 18-wheeler drifts into your lane. The highlight of the trip is my favorite restaurant sign in Tacoma.


On my drive I was mentally thinking about a self-modifying list using the R language. R is an old language used for data analysis but interest in R has grown dramatically over the past two years because of the increased collection of data in software systems.


When I got to Portland, I coded up my thoughts. My demo code defines an R list that represents a person:

# personDef.R
# a self-modifying list defining a person

person <- list(
lastName = "NONAME",
age = -1,
payRate = 0.00,

display = function() {
cat("LastName:", person$lastName, "\n")
cat("Age :", person$age, "\n")
cat("PayRate :", person$payRate, "\n")

init = function(ln, a, pr) {
person$lastName = ln
person$age = a
person$payRate = pr

There are three fields: lastName, age, and payRate. But R lists can contain functions too so I add a display() function and an init() function that can modify the list.

Calling the self-modifying list starts with:


LastName: NONAME
Age : -1
PayRate : 0

First I delete all existing objects in memory, then I point to the location of the file that has my list definition, then I execute the definition code using the source() command. The person list is created and I show it using the display() function.


person = person$init("Adams", as.integer(22), 22.22)
p1 <- person

LastName: Adams
Age : 22
PayRate : 22.22

I modify the list using the init() function. The key is that the definition returns the list itself and I use assignment (person = person( . . ) in the call. Then I copy the person list into a p1 object.

Then I repeat the process to create a second person:

person = person$init("Baker", as.integer(33), 33.33)
p2 <- person
LastName: Baker
Age : 33
PayRate : 33.33

There were two motivations for this mental exercise. First, I wanted to see if I could use this mechanism to simulate a super lightweight R language OOP paradigm rather than using the S3, S4, or R6 packages. It looks like the answer is "yes". The second motivation was to entertain myself on The Slog after seeing my favorite $1 Chinese Food sign.

This entry was posted in Machine Learning, R Language. Bookmark the permalink.