[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
addnode<-function(tree, key, data){

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

        }
	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,"Java","compulsory object system")
> a<-addnode(a,"C","No built-in support but that needn't stop you")
> a<-addnode(a,"C++","If C++ is your hammer, everything looks like a
thumb")
> applyinorder(a,function(key,data) paste(key,data,sep=": "))
[1] "C: No built-in support but that needn't stop you"
[2] "C++: If C++ is your hammer, everything looks like a thumb"
[3] "Java: compulsory object system"
[4] "R: two optional method systems and first-class functions"




More information about the R-help mailing list