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
我有我在这里简单的东西的感觉不一致。 任何帮助非常感谢!
啊,就这么简单。我也会看看Reference Class。 –