gpt4 book ai didi

r - 如何在 R 中自动更新 S4 类的插槽

转载 作者:行者123 更新时间:2023-12-05 01:00:13 31 4
gpt4 key购买 nike

我在 R 中使用 S4 对象并想知道以下问题:

让我们假设以下简化示例:我们在 R 中有两个 S4 类,一个名为 客户 和另一个 订购 .我们使用以下插槽定义它们:

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 有两列,“描述”和“成本”,我如何自动更新一个新的订单实例?有没有一种优雅/通用的方法来做到这一点?最有可能的是,Order 类需要一个类型为“Customer”的槽。提前谢谢了

最佳答案

您无法链接两个独立的对象,因此您需要使用两者的方法。这是一个带有替换方法的示例:

Customer <- setClass(
"Customer",
slots=c(
CustomerID="numeric",
Name="character",
OrderHistory="list"
),
prototype=list(OrderHistory = list())
)
Order <- setClass(
Class="Order",
slot =c(
Description="character", Cost="numeric"
) )

setGeneric(
"add<-",
function(object, value, ...) StandardGeneric("add<-")
)
setMethod("add<-", c("Customer", "Order"),
function(object, value) {
object@OrderHistory <- append(object@OrderHistory, value)
object
}
)
setMethod("show", "Customer",
function(object) {
cat("** Customer #", object@CustomerID, ": ", object@Name, "\n\n", sep="")
for(i in object@OrderHistory) cat("\t", i@Description, "\t", i@Cost, "\n", sep="")
}
)

firstCustomer <- new("Customer", CustomerID=1, Name="test")
add(firstCustomer) <- new("Order", Description="new iPhone", Cost=145)
add(firstCustomer) <- new("Order", Description="macbook", Cost=999)

firstCustomer

产生:
** Customer #1: test

new iPhone 145
macbook 999

关于r - 如何在 R 中自动更新 S4 类的插槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29779909/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com