我试图修改一个自编写类定义的对象的内容,该函数接受该类的两个对象并添加内容。
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上的研究一致,
R中的引用调用(使用函数修改对象)
并使用讲座中的代码(用德语注释和编写)
我现在想用下面的方法得到一个类似的结果:
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
不一致。我觉得我错过了一些简单的东西。任何帮助都非常感激!
我不记得为什么了,但是对于<-函数,最后一个参数必须命名为'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类。