############################################################### # Solutions to Worksheet from Chap. 8 # # Programming Functions and Object-Oriented Programming in R # ############################################################### # B- Organizing graphical objects # 8.1- Window <- function(x=0,y=0,width=2,height=2,log="") { obj <- list(x=x,y=y,width=width,height=height,log=log) class(obj) <- "Window" obj } # 8.2- Circle <- function(x=0,y=0,radius=0.5) { circle <- list(x=x,y=y,radius=radius) class(circle) <- "Circle" circle } Rectangle <- function(x=0,y=0,width=1,height=height) { rectangle <- list(x=x,y=y,width=width,height=height) class(rectangle) <- "Rectangle" rectangle } # 8.3- plot.Window <- function(obj) { plot.new() plot.window(xlim=obj$x+c(-1,1)*obj$width/2, ylim=obj$y+c(-1,1)*obj$height/2,obj$log,asp=1) } plot.Rectangle <- function(rectangle) { rect(rectangle$x-rectangle$width/2,rectangle$y- rectangle$height/2,rectangle$x+rectangle$width/2, rectangle$y+rectangle$height/2) } plot.Circle <- function(circle) { symbols(circle$x,circle$y,circle=circle$radius, inches=FALSE,add=TRUE) } # 8.4- mywindow <- Window(0,0,2,2) mycircle <- Circle(0,0,.5) myrectangle <- Rectangle(0,0,1,1) plot(mywindow);plot(mycircle);plot(myrectangle) # 8.5- MyPlot <-function(x=0,y=0,width=2,height=2,log="") { graph <- list(objets=list()) class(graph) <- "MyPlot" graph } # 8.6- add.MyPlot <- function(graph,...) { graph$objects <- c(graph$objects,list(...)) graph } add <- function(obj,...) UseMethod("add") plot.MyPlot <- function(graph) { for(object in graph$objects) { plot(object) } } graph <- MyPlot() graph <- add(graph,Window(0,0,2,2),Circle(0,0,.5), Rectangle(0,0,1,1)) plot(graph) # 8.7- MyPlot <- function(...,x=0,y=0,width=2,height=2,log="") { graph <- list(objets=list()) class(graph) <- "MyPlot" graph <- add(graph,Window(x,y,width,height,log),...) graph } graph <- MyPlot(Circle(),Rectangle()) plot(graph) # 8.8- display <- function(obj,...) UseMethod("plot") graph <- MyPlot(Circle(),Rectangle()) display(graph) # 8.9- Your turn to play!