R S4 objects and overloaded data.frame

Here is some code extracted from this answer http://stackoverflow.com/a/14607290 to the question “How to create a dataframe of user defined S4 classes in R“. The answer and question are well worth reading, but I wanted to have the code example in one place without the intervening comments:

# Create S4 class person(name,age)
setClass("person", 
  slots = c(
    name="character", 
    age="numeric"
  )
)

# Create subsetting operator
setMethod("[", 
  "person",
  function(x, i, j) {
    initialize(x, name=x@name[i], age=x@age[i])
  }
)

# Create overload for format()
format.person <- function(x) {
  paste0(x@name, ", ", x@age)
}

# Create overload for as.data.frame()
as.data.frame.person <-
  function(x, row.names=NULL, optional=FALSE)
{
  if (is.null(row.names))
    row.names <- x@name
    value <- list(x)
    attr(value, "row.names") <- row.names
    class(value) <- "data.frame"
    return(value)
}

# Create overload for c()
c.person = function(...) {
  args = list(...)
  return(
    new("person",
      name=sapply(args, function(x) x@name),  
      age=sapply(args, function(x) x@age)
    )
  )
}

# Demonstrate the code above; writes "John, 20"
format(
    data.frame(
        c(
            new("person", name="Tom", age=30),
            new("person", name="John", age=20)
        )
    )[2,]
)