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 "Movie", slots = list( title = "character", rating = "numeric", runTime = "integer" ) ) cat("\nBegin list of objects demo \n\n") movies = list() # movies = new("Movie", "Ant-Man", 8.1, # as.integer(117)) # 'cannot use integer' movies = new("Movie", title="Ant-Man", rating=8.1, runTime=as.integer(117)) movies = new("Movie") movies[]@title = "Brazil" movies[]@rating = 8.2 movies[]@runTime = as.integer(99) Book = setRefClass( # RC "Book", fields = list( title = "character", price = "numeric", pages = "integer" ) ) books = list() # books = Book$new("AAA", 11.11, # as.integer(111)) # RC unnamed args error books = Book$new(title="AAA", price=11.11, pages=as.integer(111)) books = Book$new() books[]$title = "BBB" books[]$price = 22.22 books[] = as.integer(222) cat("\nEnd demo \n\n")