将特定插槽定义为单独的类 R



我的目标是将类安全的一个插槽定义为另一个类 Quote。

首先,我定义类引用:

Quote <- setClass("Quote", slots = c(Last = "numeric", Settle = "numeric"))

然后我尝试将类安全性定义为如下:

Security <- setClass("Security", slots = c(Name = "character", Price = "Quote"))

最后,我正在尝试为类安全性创建构造函数:

Security <- function(Name = character(), Last = numeric(), Settle = numeric()) 
 new("Security", Name = Name, Price@Last = Last, Price@Settle = Settle)

不幸的是,这段代码不起作用...

提前谢谢。

如果为用户提供名为 Security 的构造函数,请确保默认构造函数的名称不同

.Security <- setClass("Security", slots = c(Name = "character", Price = "Quote"))

在您自己的构造函数中,创建槽实例作为默认构造函数的参数;使用 ... 允许类继承

Security <- 
    function(Name = character(), Last = numeric(), Settle = numeric(), ...)
{
    .Security(Name=Name, Price=Quote(Last=Last, Settle=Settle), ...)
}

我还在尝试学习 S4,我看到一位公认的专家已经给出了答案,所以我主要将此作为批评示例发布:

.Quote <- setClass("Quote", slots = c(Last = "numeric", Settle = "numeric"))
.Security <- setClass("Security", slots = c(Name = "character", Price = "Quote"))
 aNewSecurity <- .Security(Name = "newSec", 
                           Price = .Quote(Last =20, Settle = 40) )
 aNewSecurity
An object of class "Security"
Slot "Name":
[1] "newSec"
Slot "Price":
An object of class "Quote"
Slot "Last":
[1] 20
Slot "Settle":
[1] 40

我没有足够的知识来知道此域是否需要将报价项与安全项分开。

最新更新