Created
December 11, 2015 18:31
-
-
Save saurfang/a90dbfb175cc02fb0a49 to your computer and use it in GitHub Desktop.
S3 example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```{r} | |
area <- function(x) UseMethod("area", x) | |
rectangle <- function(a, b) { | |
structure(list(a = a, b = b), class = "rectangle") | |
} | |
area.rectangle <- function(x) { | |
x$a * x$b | |
} | |
circle <- function(r) { | |
structure(list(r = r), class = "circle") | |
} | |
area.circle <- function(x) { | |
pi * x$r * x$r | |
} | |
``` | |
Now calculating area: | |
``` | |
area(rectangle(2, 4)) | |
area(circle(3)) | |
``` | |
We can also define print | |
``` | |
as.character.rectangle <- function(x) { | |
"rectangle" | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment