R Language Arrays and Lists of Objects

A common programming pattern is to create a collection of objects, for example an array of Movie objects or a list of Book objects. I took a close look at this programming task in the R language. I conclude that R supports lists of S4 or RC objects fairly well (but there are some syntax quirks) but R does not support arrays or vectors, or lists of S3 objects well. In other words, if you need a collection of objects in R, use a list of either S4 or RC objects.


The demo program below creates an S4 Movie class and then a list with two Movie objects. When using the S4 “new()” you must use named arguments if there is an integer field. And you need to use double square brackets to access fields of an object in a list.

The demo creates an RC Book class and a list with a couple of Book objects. The same quirks apply.

It’s not convenient to create an array of objects because R arrays are intended only to hold atomic types such as “numeric”. And it’s not convenient to create a vector of objects for the same reason, and using the as.vector() function needs a list as an argument so you might as well just use the list.

# listsOfObjects.R
# R 3.2.3

Movie = setClass(  # S4
  slots = list(
    title = "character",
    rating = "numeric",
    runTime = "integer"

cat("\nBegin list of objects demo \n\n")

movies = list()
# movies[1] = new("Movie", "Ant-Man", 8.1,
#  as.integer(117)) # 'cannot use integer'
movies[1] = new("Movie", title="Ant-Man",
 rating=8.1, runTime=as.integer(117))

movies[2] = new("Movie")
movies[[2]]@title = "Brazil"
movies[[2]]@rating = 8.2
movies[[2]]@runTime = as.integer(99)

Book = setRefClass(  # RC
  fields = list(
    title = "character",
    price = "numeric",
    pages = "integer"

books = list()
# books[1] = Book$new("AAA", 11.11,
#   as.integer(111))  # RC unnamed args error
books[1] = Book$new(title="AAA", price=11.11,

books[2] = Book$new()
books[[2]]$title = "BBB"
books[[2]]$price = 22.22
books[[2]] = as.integer(222)

cat("\nEnd demo \n\n")
This entry was posted in Machine Learning, R Language. Bookmark the permalink.