2011-03-25 4 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의 구현보다 쉽습니다).
다음은 정의 (즉 필드 length 때문에 이름 중복의 len로 대체 주)입니다 :

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

+0

온라인 도움말>? setRefClass 및 여기 : http://www.slideshare.net/romainfrancois/object-oriented-designs-in-r – kohske