Is it possible to get the syntax
foo$bar(x) <- value
to work where foo
is a reference class object and bar
is a method?
I.e. is it possible to do "subset assigment" and have "replacement functions" as methods in Reference Classes?
Is the syntax possible to get with other OO systems?
Example:
I'll illustrate with a made-up use case. Imagine a reference class, Person
, which contains some basic information of a person. Particularly, one field called fullname
is a named list
:
PersonRCGen <- setRefClass("Person",
fields = list(
fullname = "list",
gender = "character"
))
Next, we should define some methods to get and set particular names within the fullnames
list which (try) to give the above syntax/interface. My best attempt has so far been:
PersonRCGen$methods(
name = function(x) { # x is the dataset,
.self$fullname[[x]]
},
`name<-` = function(x, value) {
.self$fullname[[x]] <- value
}
)
The naming here should also illustrate what I'm trying to do.
We initialize a new object:
a_person <- PersonRCGen$new(fullname = list(first = "Jane", last = "Doe"),
gender = "F")
Accessing the fullname
field directly and accessing the first and last name by the defined get-function works as intended:
a_person$fullname
#$`first`
#[1] "Jane"
#
#$last
#[1] "Doe"
a_person$name("first")
#[1] "Jane"
a_person$name("last")
#[1] "Doe"
However, for setting a particular name in the fullname
list, I'd like to have the following syntax/interface which unfortuantely fails.
a_person$name("first") <- "Jessie"
#Error in a_person$name("first") <- "Jessie" :
# target of assignment expands to non-language object
I know the following works (which basically renders the method poorly named).
a_person$`name<-`("first", "Johnny")
a_person$fullname
#$`first`
#[1] "Johnny"
#
#$last
#[1] "Doe"
In my real use case, I'd like to avoid 'traditional' getName(x)
and setName(x, value)
names for the get and set functions.
$<-
is a synonym for[[<-
, although you code suggests you might have already understood that. – Auroraassign
-function or<-
which of course also is a function. As for$<-
and[[<-
, I'd say these are examples of 'assignment functions' in a subsetting context. I was more asking for a name for all'foo<-'(x, value)
functions which admits to thefoo(x) <- value
syntax. So I would looking for a more specific name (if it exists) for functions of this type if you will. In other words, how do I google it? – Avilla[[<-
as you suggested), and this led me here and here. So the names seems to be 'replacement functions' or 'subset assigment'. – Avillanames(1:10)<-letters[1:10]
doesn't work. The assignment functions work if the first argument is already assigned and it's the object that gets modified/replaced. – Konstanz'names<-'(1:10, letters[1:10])
works just fine (like in the case above). – Avilla