Here is a reference class implementation, as suggested in one of the comments. The basic idea is to set up a reference class called Stores
that has three fields: apples
, pears
and fruits
(edited to be an accessor method). The initialize
method is used to initialize a new store, the addApples
method adds apples to the store, while the show
method is equivalent to print
for other objects.
Stores = setRefClass("Stores",
fields = list(
apples = "numeric",
pears = "numeric",
fruits = function(){apples + pears}
),
methods = list(
initialize = function(apples, pears){
apples <<- apples
pears <<- pears
},
addApples = function(i){
apples <<- apples + i
},
show = function(){
cat(apples, "apples and", pears, "pears")
}
)
)
If we initialize a new store and call it, here is what we get
FruitStore = Stores$new(apples = 3, pears = 4)
FruitStore
# 3 apples and 4 pears
Now, invoking the addApples
method, let us add 4 apples to the store
FruitStore$addApples(4)
FruitStore
# 7 apples and 4 pears
EDIT. As per Hadley's suggestion, I have updated my answer so that fruits
is now an accessor method. It remains updated as we add more apples
to the store. Thanks @hadley.