1

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

首先我定义类引用:

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

然后我试图定义类安全如下:

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

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

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

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

提前致谢。

4

2 回答 2

1

如果为用户提供名为 的构造函数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), ...)
}
于 2013-10-10T18:24:26.917 回答
0

我还在努力学习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

我没有足够的知识知道在此域中是否需要将 Quote 项与 Security 项分开。

于 2013-10-10T18:31:00.097 回答