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.