[R] truly object oriented programming in R

Seth Falcon sfalcon at fhcrc.org
Thu Aug 12 19:53:37 CEST 2004


Hi Jason,

On Thu, Aug 12, 2004 at 10:20:14AM -0700, Jason Liao wrote:
> Does R's list support this recursive data structure? If yes, can you
> give a sample program?

Not sure if this is what you are looking for, but here's a quick linked
list example using R's lists.

# ---------------------8<---------------------------
newNode <- function(value) {
  list(data=value, child=NULL)
}

insertNode <- function(headNode, node) {
  node$child <- headNode
  node
}

printNodes <- function(headNode) {
  curNode <- headNode
  while (TRUE) {
    print(curNode$data)
    if (is.null(curNode$child ))
      break
    curNode <- curNode$child
  }
}

head <- newNode(1)
head <- insertNode(head, newNode(2))
head <- insertNode(head, newNode(3))
head <- insertNode(head, newNode(4))

printNodes(head)
# ---------------------8<---------------------------

The thing that's very different from, say, Java is that everything is an
object in R --- there isn't a notion of a *reference* to an object,
which is why in the above I had to say "head <- insertNode(...)" where
as in Java you could pass in a reference to head and have the method
modify what it points to.

I think there are some ways around this, at least syntactically, using
various tricks with environment(), but I don't yet understand them well
enough to comment further.

hope that's helpful,

+ seth




More information about the R-help mailing list