2011-03-25 53 views
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) 

感谢您的帮助。

回答

2

也许这不是你想要的,但可能R5类适合你的目的,因为你需要通过引用函数调用。

很容易从S4类重写R5类(并且R5中的实现比S4中的更容易)。
这里是一个定义(注意,场lengthlen替换,因为名称重复):

ProtectedRObjectList <- setRefClass(
    "ProtectedRObjectList", 
    fields = list(objectList = "list", keys = "character", len = "numeric"), 
    methods=list(
    getNewSlot = function(){ 
     if(length(len)==0) 
     { 
     #initial case 
     len <<- 0; 
     } 
     #update list length and generate random key 
     len<<-len + 1; 
     keys[len]<<-paste(sample(c(letters, LETTERS), 15, replace =TRUE), collapse = ""); 
     #return "index, key" pair 
     return(list("index" = len, "key" = keys[len])) 
    } 
) 
) 

与用法:

> thisObj<-ProtectedRObjectList$new() 
> thisObj 
An object of class "ProtectedRObjectList" 
<environment: 0x116207c30> 
> thisObj$len 
numeric(0) 
> thisObj$keys 
character(0) 
> 
> output<-thisObj$getNewSlot() 
> output 
$index 
[1] 1 

$key 
[1] "GeCyCTdIflcYFbE" 

> 
> thisObj$len 
[1] 1 
> thisObj$keys 
[1] "GeCyCTdIflcYFbE" 
+0

感谢。这很好。我没有听说过R5类。你知道文档的好来源吗? – jmmcnew 2011-03-28 14:09:11

+0

在线帮助>?setRefClass和此处:http://www.slideshare.net/romainfrancois/object-oriented-designs-in-r – kohske 2011-03-28 23:36:05