我正在尝试使用一个函数修改一个自写类定义的对象的内容,该函数接受此类的两个对象并添加内容。
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/