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:
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: drunken walk, oop, r, random walk
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
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