Skip to content

Instantly share code, notes, and snippets.

@saurfang
Created December 11, 2015 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saurfang/a90dbfb175cc02fb0a49 to your computer and use it in GitHub Desktop.
Save saurfang/a90dbfb175cc02fb0a49 to your computer and use it in GitHub Desktop.
S3 example
```{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