r - 用 "call by reference"修改对象的内容

标签 r oop

我正在尝试使用一个函数修改一个自写类定义的对象的内容,该函数接受此类的两个对象并添加内容。

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 上的研究一致,
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) {
    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
我觉得我在这里缺少一些简单的东西。 非常感谢任何帮助!

最佳答案

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

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 类来避免传统的参数作为值的事情。

关于r - 用 "call by reference"修改对象的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22500536/

相关文章:

r - 如何根据 knitr 中的条件包含标题

r - 正半定矩阵Cholesky分解中pivot的正确使用

java - 自动调用已实现的方法?

c++ - 在复合模式中搜索特定元素

r - 如何以智能方式将互联网上的图像插入到 R bookdown 生成的 pdf 文件中?

r - 计算整数位数

rpy2 importr 因 xts 和 quantmod 失败

javascript - 不同的对象类型

oop - Go 结构中的 omitempty 用例有哪些?

scala - 特征混合与冲突成员 : Why my code can be compiled successfully?