我是R中的面向对象编程的新手,并且很难与正确编写修改对象的函数编写。修改S3对象而不返回它?
这个例子的工作原理:
store1 <- list(
apples=3,
pears=4,
fruits=7
)
class(store1) <- "fruitstore"
print.fruitstore <- function(x) {
paste(x$apples, "apples and", x$pears, "pears", sep=" ")
}
print(store1)
addApples <- function(x, i) {
x$apples <- x$apples + i
x$fruits <- x$apples + x$pears
return(x)
}
store1 <- addApples(store1, 5)
print(store1)
但我想应该这样做,而无需返回整个对象更清洁的方式:
addApples(store1, 5) # Preferable line...
store1 <- addApples(store1, 5) # ...instead of this line
是编写修改函数的正确方法在R? “< < - ”?
更新:非常感谢您为什么成为R的OOP罗塞塔石。非常丰富。 我试图解决的问题在流程方面非常复杂,因此参考类的刚性可能会带来结构的帮助。我希望我能够接受所有答案作为答案,而不仅仅是答案。
如果你真的想修改位置,那么也许你不应该使用S3对象,而是[引用类](http://adv-r.had.co.nz/OO-essentials。 html#rc)对象。 – Andrie
好评。参考类的目的突然有意义。 – Chris