我的目标是将Security类中的一个插槽定义为另一个类Quote。
首先我定义类Quote:
Quote <- setClass("Quote", slots = c(Last = "numeric", Settle = "numeric"))
然后我尝试将类Security定义如下:
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)
不幸的是,这段代码不起作用......
提前致谢。
答案 0 :(得分: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), ...)
}
答案 1 :(得分: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
我不太了解是否需要在此域中将安全项目中的引用项目分开。