[R] truly object oriented programming in R

Thomas Lumley tlumley at u.washington.edu
Thu Aug 12 20:47:23 CEST 2004

```On Thu, 12 Aug 2004, Jason Liao wrote:

> Dear Thomas,
> Thank you very much again for taking time to answer my questions. I am
> sorry that my knoweldge of R is limited as I have only learned what is
> necessary to do my work. In the KD tree, we have this recursive data
> structure in that each knod has two children knods and this process
> continues until the data points are divided. Does R's list support this
> recursive data structure? If yes, can you give a sample program?

Yes, the elements of a list can be lists. For example, a simple binary
tree could have lists with elements left, right, key, and data

## create a new single node
newtree<-function(key,data){ list(left=NULL,right=NULL, key=key,
data=data)}

## add a node to a sorted tree

if (key<=tree\$key){
if (is.null(tree\$left))
tree\$left<-newtree(data=data,key=key)
else
} else {
if (is.null(tree\$right))
tree\$right<-newtree(data=data,key=key)
else

}
return(tree)
}

## inorder traversal.  action() is any function that takes key and data
## arguments
applyinorder<-function(tree, action){

c(if (!is.null(tree\$left))
applyinorder(tree\$left,action),
action(tree\$key,tree\$data),
if (!is.null(tree\$right))
applyinorder(tree\$right, action))

}

## an example
> a<-newtree("R","two optional method systems and first-class functions")
> a<-addnode(a,"C","No built-in support but that needn't stop you")