R: A random walk though OOP land.

If you are used to object oriented programing in a different language, the way R does things can seem a little strange and backwards. “proto” to the rescue. With this library you can simulate “normal” OOP. I found the examples for proto not so helpful, so to figure out how the package works I sent one lonely red ant on a drunken walk. Here’s my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
library("proto")
 
# Everybody likes ants
ant <- proto(
	# Default values for the class variables
	xPos = 0,            
	yPos = 0,
	name = character(),      
)
 
# What do ants do? They move
ant$move <-function(.,xDisp=0, yDisp=0) {
	.$xPos = .$xPos + xDisp
	.$yPos = .$yPos + yDisp
}
 
# See the little red ant move
ant$plot <- function(.) {
	points(.$xPos, .$yPos, pch=20, col="red")
}
 
# Instantiate the class. 
myAnt = ant
myAnt$name = "George"
 
 
plot(myAnt$xPos, myAnt$yPos, xlim=c(-10,10), ylim=c(-10,10), pch=20, col="red")
for(i in 1:40) {
 
	# The ant is drunk on Kool Aid
	myAnt$move(rnorm(1),rnorm(1))
 
	# The ant is lazy and will rest for a moment
	Sys.sleep(.5)
 
	# Plot the new location
	ant$plot()
 
}
 
cat("The ant named", myAnt$name, "is now located at (", myAnt$xPos, myAnt$yPos, ")\n")

Tags: , , ,

2 comments

  1. Good post!
    Keep up such posts :)

    Also, I see that Proto can plot the objects relationships – it might be worth to add a note about that.
    http://code.google.com/p/r-proto/wiki/Overview

    p.s: I am glad you started using the R syntax highlight plugin :)

    Cheers,
    Tal

  2. Thanks Tal!

    The R syntax plugin you mentioned works well, but it looks like all of the line numbers show up as the beginning of the code on your r-bloggers page as if they were code. Is there any way to fix that without me removing the line number option?

    Cheers,

    Matt

Leave a comment