【发布时间】:2015-04-21 18:06:24
【问题描述】:
我在 R 中玩 S4 对象,想知道以下问题:
假设以下简化示例:我们在 R 中有两个 S4 类,一个称为 Customer,另一个称为 Order。我们使用以下插槽定义它们:
Customer <- setClass(Class = "Customer",slots = c(CustomerID = "numeric", Name = "character", OrderHistory = "data.frame"),
prototype = list(CustomerID = 0,Name = "",OderHistory = data.frame()))
Order <- setClass(Class = "Order",slots = c(CustomerID = "numeric", Description = "character",
Cost = "numeric"),
prototype = list(CustomerID = 0,Description = "",Cost = 0))
# constructor
Customer <- function(CustomerID, Name, OrderHistory=data.frame()){
#drop sanity checks
new("Customer",CustomerID = CustomerID, Name = Name, OrderHistory = OrderHistory)
}
Order <- function(CustomerID, Description = "",Cost = 0){
#drop sanity checks
new("Order",CustomerID = CustomerID, Description = "", Cost = 0)
}
#create two objects
firstCustomer <- Customer(1,"test")
firstOrder <- Order(1,"new iPhone", 145)
显然,firstCustomer 和 firstOrder 是通过 CustomerID 链接的。是否可以在创建新的 Order 实例后自动更新 Customer 的 OrderHistory 槽?假设 OrderHistory 有两列,“Description”和“Cost”,我怎样才能自动更新一个新的订单实例?有没有一种优雅/通用的方法来做到这一点?最有可能的是,订单类需要一个“客户”类型的插槽。非常感谢提前
【问题讨论】: