2014-03-19 31 views
3

我試圖修改一個自定義類的對象的內容,該對象使用一個帶有這個類的兩個對象並添加內容的函數。用「通過引用調用」修改對象的內容

setClass("test",representation(val="numeric"),prototype(val=1)) 

我知道的是,R不是真的有作品「呼叫參考」,但可以模仿像這樣一個方法,該方法的行爲:

setGeneric("value<-", function(test,value) standardGeneric("value<-")) 
setReplaceMethod("value",signature = c("test","numeric"), 
    definition=function(test,value) { 
    [email protected] <- value 
    test 
    }) 
foo = new("test") #[email protected] is 1 per prototype 
value(foo)<-2 #[email protected] is now set to 2 

直到這裏,任何事情我沒有和得到的結果是consitent與我的研究在這裏stackexchange,
Call by reference in R (using function to modify an object)
this code從講座(評論和書面德語)

我現在想實現的是類似的結果有以下方法:

setGeneric("add<-", function(testA,testB) standardGeneric("add<-")) 
setReplaceMethod("add",signature = c("test","test"), 
    definition=function(testA,testB) { 
    [email protected] <- [email protected] + [email protected] 
    testA 
    }) 
bar = new("test") 
add(foo)<-bar #should add the value slot of both objects and save the result to foo 

Instead I get the following error: 
Error in `add<-`(`*tmp*`, value = <S4 object of class "test">) : 
    unused argument (value = <S4 object of class "test">) 

函數調用可與:

"add<-"(foo,bar) 

但這並不值保存到foo中。使用

foo <- "add<-"(foo,bar) 
#or using 
setMethod("add",signature = c("test","test"), definition= #as above...) 
foo <- add(foo,bar) 

作品,但這是與改性方法value(foo)<-2
我有我在這裏簡單的東西的感覺不一致。 任何幫助非常感謝!

回答

0

我不記得爲什麼,但對於<函數,最後一個參數必須命名爲'value'。 所以你的情況:

setGeneric("add<-", function(testA,value) standardGeneric("add<-")) 
setReplaceMethod("add",signature = c("test","test"), 
    definition=function(testA,value) { 
    [email protected] <- [email protected] + [email protected] 
    testA 
    }) 
bar = new("test") 
add(foo)<-bar 

您也可以IG要避免傳統參數作爲值東西使用Reference類。

+0

啊,就這麼簡單。我也會看看Reference Class。 –