2012-01-20 16 views

Trả lời

12

đây là một ví dụ:

setClass("yyy", representation(v="numeric")) 

setMethod("+", signature(e1 = "yyy", e2 = "yyy"), function (e1, e2) [email protected] + [email protected]) 
setMethod("+", signature(e1 = "yyy", e2 = "numeric"), function (e1, e2) [email protected] + e2) 

sau đó,

> y1 <- new("yyy", v = 1) 
> y2 <- new("yyy", v = 2) 
> 
> y1 + y2 
[1] 3 
> y1 + 3 
[1] 4 
+0

đó là nhờ chỉ hoàn hảo (và rất thanh lịch) – RockScience

16

Nhà điều hành + là một phần của nhóm Arith generic (xem ?GroupGenericFunctions) để người ta có thể thực hiện tất cả các chức năng trong nhóm với

setMethod("Arith", "yyy", function(e1, e2) { 
    v = callGeneric([email protected], [email protected]) 
    new("yyy", v = v) 
}) 

và sau đó với

setClass("yyy", representation(v="numeric")) 
setMethod(show, "yyy", function(object) { 
    cat("class:", class(object), "\n") 
    cat("v:", [email protected], "\n") 
}) 
setMethod("Arith", "yyy", function(e1, e2) { 
    v = callGeneric([email protected], [email protected]) 
    new("yyy", v = v) 
}) 

Một sẽ phải

> y1 = new("yyy", v=1) 
> y2 = new("yyy", v=2) 
> y1 + y2 
class: yyy 
v: 3 
> y1/y2 
class: yyy 
v: 0.5 
## ...and so on 
+0

Liệu đó là giả định rằng bạn muốn áp dụng + nhà điều hành cho tất cả các khe của đối tượng? – RockScience

+1

Nó đang tái gửi đến toán tử số học cho vị trí 'v' của các đối tượng e1 và e2. Nếu có các khe v và w, bạn có thể viết cho phần thân của phương thức 'new (" yyy ", v = callGeneric (e1 @ v, e2 @ v), w = callGeneric (e1 @ w, e2 @ w)) ' –