Automatic assignment in initialize () methods for reference classes in R

I work with a reference class with several dozen fields. I set the initialize() method, which takes a list object. Although some of the fields rely on further calculations from list items, most fields are directly assigned from list items as such:

 fieldA <<- list$A fieldB <<- list$B 

I thought it would be nice to automate this a bit. To give an example in the pseudocode R (this example obviously will not work):

 for (field in c('A', 'B', 'C', 'D')) field <<- list[[field]] 

I tried to make a few end runs around <<- , for example by doing something like:

 for field in c('A', 'B', 'C', 'D')) do.call('<<-' c(field, list[[field]])) 

but not bones.

I suppose that this kind of behavior is simply not possible in the current incarnation of the reference classes, but I thought it might be worth a look if anyone from the Land of the Lands knows the best way to do this.

+7
source share
1 answer

Use .self to specify an instance, and select fields using [[ . I am not 100% sure (but who ever is?) That [[ is strictly legal. I added the defaults to lst , so it works when called as C$new() , an implied assumption in S4 that looks like bites are similar to reference classes.

 C <- setRefClass("C", fields=list(a="numeric", b="numeric", c="character"), methods=list( initialize=function(..., lst=list(a=numeric(), b=numeric(), c=character()) { directflds <- c("a", "b") for (elt in directflds) .self[[elt]] <- lst[[elt]] .self$c <- as.character(lst[["c"]]) .self })) c <- C$new(lst=list(a=1, b=2, c=3)) 

Or leave the option to pass the list or the items themselves to the user using

 B <- setRefClass("B", fields=list(a="numeric", b="numeric", c="character"), methods=list( initialize=function(..., c=character()) { callSuper(...) .self$c <- as.character(c) .self })) b0 <- B$new(a=1, b=2, c=3) b1 <- do.call(B$new, list(a=1, b=2, c=3)) 

It also seems more tolerant of excluding certain values ​​from the new() call.

+5
source

All Articles