An example of passing matrix by reference in R using the R6 framework
library(R6)
library(pryr)
# Class defining a storage for a local matrix
LocalMatrix <- R6Class("LocalMatrix", public = list(x = NULL))
# Class defining a container for a shared matrix
SharedMatrix <- R6Class("SharedMatrix", public = list(e = LocalMatrix$new()))
# Initialize a shared container containing a local matrix and print it
o1 <- SharedMatrix$new()
o1$e$x <- matrix(1, 13, 12)
o1$e$x
# Create a "new" shared matrix and update the local matrix in position 2,3 with the value 5
o2 <- SharedMatrix$new()
o2$e$x[2:10,3:6]<-5
# Changing o2$e$x has changed the value of o1$e$x
o1$e$x
# Create a list of a 1000 ShareMatrix
myl<-list()
for(i in 1:1000) myl[[i]]<-SharedMatrix$new()
# See the size
print(paste("Object o1 is of size: ", object_size(o1)))
print(paste("Object o2 is of size: ", object_size(o2)))
print(paste("Object myl is of size: ", object_size(myl)))
print(paste("A list of a 1000 sharedMatrix takes up only: ", object_size(o1)*1000))
# Timing stuff (around a factor 11 times faster for 1000 replications)
stmp<-SharedMatrix$new()
stmp$e$x<-matrix(1, 500, 100)
system.time({myl<-list(); for(i in 1:1000) myl[[i]]<-SharedMatrix$new()})
system.time({myl<-list(); for(i in 1:1000) myl[[i]]<-matrix(1, 500, 100)})