[This article was first published on Probability and statistics blog » r, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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") |
To leave a comment for the author, please follow the link and comment on their blog: Probability and statistics blog » r.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.