I'm new to object-oriented programming in R and struggle with how to properly write a function that modifies an object.
This example works:
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)
But I suppose there should be a cleaner way to do this without returning the whole object:
addApples(store1, 5) # Preferable line...
store1 <- addApples(store1, 5) # ...instead of this line
What is the proper way to write modify-functions in R? "<<-"?
Update: Thank you all for what became a Rosetta Stone for OOP in R. Very informative. The problem I'm trying to solve is very complex in terms of flow, so the rigidness of reference classes may bring the structure to help. I wish I could accept all responses as answers and not only one.
Here is a reference class implementation, as suggested in one of the comments. The basic idea is to set up a reference class called
Storesthat has three fields:apples,pearsandfruits(edited to be an accessor method). Theinitializemethod is used to initialize a new store, theaddApplesmethod adds apples to the store, while theshowmethod is equivalent toprintfor other objects.If we initialize a new store and call it, here is what we get
Now, invoking the
addApplesmethod, let us add 4 apples to the storeEDIT. As per Hadley's suggestion, I have updated my answer so that
fruitsis now an accessor method. It remains updated as we add moreapplesto the store. Thanks @hadley.