11
A
回答
12
這裏是一個例子:
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)
然後,
> y1 <- new("yyy", v = 1)
> y2 <- new("yyy", v = 2)
>
> y1 + y2
[1] 3
> y1 + 3
[1] 4
16
的+
運算符是ARITH組通用的(見?GroupGenericFunctions
)因此可以實現該組中的所有功能與
setMethod("Arith", "yyy", function(e1, e2) {
v = callGeneric([email protected], [email protected])
new("yyy", v = v)
})
然後用
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)
})
一會還要
> 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
是,這假設要+操作適用於對象的所有插槽? – RockScience
+1
它將重新派發給算術運算符,用於對象e1和e2的槽'v'。如果有插槽v和w,則可以寫入方法體new(「yyy」,v = callGeneric(e1 @ v,e2 @ v),w = callGeneric(e1 @ w,e2 @ w)) ' –
相關問題
- 1. 從另一個S4對象中的S4對象中提取信息R
- 2. 在R中創建S4對象
- 3. 以編程方式區分R中的S3和S4對象
- 4. 循環遍歷R中的S4對象中的列
- 5. 如何訪問R中的S4對象的插槽
- 6. R中的S4對象無法傳遞給Fortran
- 7. 在Rcpp中創建R S4類的對象?
- 8. R S4應用於類中對象列表的方法
- 9. 爲R中的S4/RC對象自定義控制檯打印
- 10. 關於S4中的對象,方法和編程的源代碼R
- 11. 如何在R中使用S4對象編程
- 12. 錯誤中的R S4 setReplaceMethod
- 13. R具有S3屬性的S4對象的實例
- 14. R:從S4對象獲取插槽的值(ScalarIndependenceTest)
- 15. S4對象深度複製
- 16. tbl_df與S4對象槽
- 17. R CMD檢查期間的文檔S4類和「無證代碼對象」
- 18. 總和中的R
- 19. 總和R中
- 20. R:一個S4對象上應用terms.formula繼承data.frame
- 21. 如何分割,並寫入了S4對象的文件中的R
- 22. 總和從對象
- 23. 在R中,如何根據另一個對象的類來設置S4類
- 24. 在R中創建一個具有Zoo對象屬性的類S4 class
- 25. R中的S4類的一元加號
- 26. S4指針指向C的對象struct
- 27. 總和或R中
- 28. R是否支持S4中的集合?
- 29. 時間對象的總和
- 30. 總和JavaScript對象的
這只是完美的(和非常優雅)感謝 – RockScience