使用“按引用传递”修改对象的内容

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) {
    test@val <- value
    test
  })
foo = new("test") #foo@val is 1 per prototype
value(foo)<-2 #foo@val is now set to 2

直到现在,我所做的一切和得到的结果都与我在Stackexchange上的研究以及这个链接和这个给出的代码(德语注释)链接一致。现在我希望用以下方法获得类似的结果:
setGeneric("add<-", function(testA,testB) standardGeneric("add<-"))
setReplaceMethod("add",signature = c("test","test"),
  definition=function(testA,testB) {
    testA@val <- testA@val + testB@val
    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不一致。
我有一种感觉,好像我错过了一些简单的东西。
非常感谢您的帮助!

1个回答

0

我不记得为什么,但对于 <- 函数,最后一个参数必须命名为'value'。 所以在你的情况下:

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

如果你想避免传统的将参数作为值的方式,你也可以使用引用类(Reference class)。


啊,就这么简单。我也会看一下参考类。 - J. Beck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接