0
我需要编写一个同时更新对象并返回值的方法。我想知道在S4课程中是否有办法做到这一点。上下文是我正在尝试编写一个S4类来生成一个列表,其中的每个元素只有在知道私钥时才能被访问。为此,我需要一个方法getNewSlot,它同时更新列表和密钥列表的长度并返回索引密钥对。代码如下:在S4类中模拟地更新对象并返回值
setClass("ProtectedRObjectList",
representation(objectList = "list", keys = "character", length = "numeric"))
setGeneric(
name = "getNewSlot",
def = function(object,value){standardGeneric("getNewSlot")})
setMethod(
f = "getNewSlot",
signature = "ProtectedRObjectList",
definition = function(object){
if(length([email protected])==0)
{
#initial case
[email protected] <- 0;
}
#update list length and generate random key
[email protected]<[email protected] + 1;
[email protected][[email protected]]<-paste(sample(c(letters, LETTERS), 15, replace =TRUE), collapse = "");
#return "index, key" pair
return(list("index" = [email protected], "key" = [email protected][[email protected]]))
}
)
这是此方法的输出。如您所见,代码返回所需的“索引,键”对,但不更新对象。
> thisObj<-new("ProtectedRObjectList")
> thisObj
An object of class "ProtectedRObjectList"
Slot "objectList":
list()
Slot "keys":
character(0)
Slot "length":
numeric(0)
> output<-getNewSlot(thisObj)
> output
$index
[1] 1
$key
[1] "cjdkDvAaNjvVKdw"
> thisObj
An object of class "ProtectedRObjectList"
Slot "objectList":
list()
Slot "keys":
character(0)
Slot "length":
numeric(0)
感谢您的帮助。
感谢。这很好。我没有听说过R5类。你知道文档的好来源吗? – jmmcnew 2011-03-28 14:09:11
在线帮助>?setRefClass和此处:http://www.slideshare.net/romainfrancois/object-oriented-designs-in-r – kohske 2011-03-28 23:36:05