This section will talk about how we can use class and define the method for a class to manipulate the generic functions in R. For S4 methods, see the section S4 Methods for details.
class()
and use generic functions by using
UseMethod()
.
In R, you can define your generic functions for
print()
.
Directly input object a.1
is the same as print(a.1)
.
```
a.1 <- 3.1415926
class(a.1) <- "my.1"
a.2 <- 6.1415926
class(a.2) <- "my.2"
my.fcn <- function(x){
UseMethod("my.usefcn", x)
}
my.usefcn.my.1 <- function(x){
x + 1
}
my.usefcn.my.2 <- function(x){
x + 2
}
### First call
my.fcn(a.1)
my.fcn(a.2)
a.1
a.2
print.my.1 <- function(x, digits = 3){
print(unclass(x), digits = digits)
}
print.my.2 <- function(x, digits = 6){
print(unclass(x), digits = digits)
}
### Second call
my.fcn(a.1)
my.fcn(a.2)
print(a.1)
print(a.2)
a.1
a.2
```
At first call, my.fcn()
will return the object's attributes since
there is no default print()
function for these classes
my.1
and my.2
.
```
> my.fcn(a.1)
[1] 4.141593
attr(,"class")
[1] "my.1"
> my.fcn(a.2)
[1] 8.141593
attr(,"class")
[1] "my.2"
> a.1
[1] 3.141593
attr(,"class")
[1] "my.1"
> a.2
[1] 6.141593
attr(,"class")
[1] "my.2"
```
At second call, print.my.1()
, print.my.2()
are defined by the
class' name, so the function's returns are also followed. The
attributes are discarded in print()
by using
unclass()
.
```
> my.fcn(a.1)
[1] 4.14
> my.fcn(a.2)
[1] 8.1416
> print(a.1)
[1] 3.14
> print(a.2)
[1] 6.14159
> a.1
[1] 3.14
> a.2
[1] 6.14159
```
- Summary and Print
Here, I define some generic functions for summary()
, and
print()
,
so they can summary the results by the input's attribute and
print it by the summary's attribute, not the input's attribute.
```
summary.my.3 <- function(x){
x <- x + 10
class(x) <-"summary.3"
x
}
summary.my.4 <- function(x){
x <- x + 20
class(x) <-"summary.4"
x
}
print.summary.3 <- function(x, digits = 3){
cat("Result: ", format(x, digits = digits), "\n")
}
print.summary.4 <- function(x, digits = 6){
cat("Result: ", format(x, digits = digits), "\n")
}
a.1 <- 3.1415926
class(a.1) <- "my.3"
a.2 <- 6.1415926
class(a.2) <- "my.4"
summary(a.1)
summary(a.2)
```
The results for the summary()
.
```
> summary(a.1)
Result: 13.1
> summary(a.2)
Result: 26.1416
```
- Overwrite Operators
This is also the other silly example, but I want to demonstrate overwrite
functions in R and user defined function for binary operators.
In R, you can redefine an operator or use
%any%
to make a new one.
I define a similar operator of two sets in the following.
```
a.1 <- c("a", "b")
a.2 <- 4:7
class(a.1) <- "my.5"
### Overwrite "+" for a new class.
"+.my.5" <- function(a, b) c(a, b)
a.1 + a.2
### Define a new one.
"%union%" <- function(a, b) c(a, b)
a.1 %union% a.2
```
---